package com.ybkj.daijia.server.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.CSRFTokenManager;
import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.common.MemberOrderVo;
import com.ybkj.daijia.common.OrderLocationGroup;
import com.ybkj.daijia.common.PageVo;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.PointVo;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderCallBackEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderPaidanEvent;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerGrade;
import com.ybkj.daijia.server.mc.PassengerGradeAndArea;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.OrderLocation;
import com.ybkj.daijia.server.model.OrderLocationMany;
import com.ybkj.daijia.server.model.WeixinManagerXOrder;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderLocationManyService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.SuperviceService;
import com.ybkj.daijia.server.service.WeixinManagerService;
import com.ybkj.daijia.server.service.WeixinManagerXOrderService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.zhuan.Car;
import com.ybkj.daijia.server.zhuan.CarType;
import com.ybkj.daijia.server.zhuan.CarTypeCompany;
import com.ybkj.daijia.server.zhuan.Insurance;
import com.ybkj.daijia.server.zhuan.Order;
import com.ybkj.daijia.server.zhuan.OrderLngLat;
import com.ybkj.daijia.server.zhuan.OrderOrbit;
import com.ybkj.daijia.server.zhuan.OrderReview;
import com.ybkj.daijia.server.zhuan.OrderStatus;
import com.ybkj.daijia.server.zhuan.SelectPrice;
import com.ybkj.daijia.server.zhuan.ServiceType;
import com.ybkj.daijia.server.zhuanxian.Line;
import com.ybkj.daijia.serverUtils.CarNumberUtils;
import com.ybkj.daijia.serverUtils.ExcelUtil;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

@Controller
@RequestMapping(value = "zhuanche")
public class ZhuanCheController {

    @Autowired
    private ZhuancheService zhuancheService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private WeixinManagerService weixinManagerService;
    @Autowired
    private WeixinManagerXOrderService weixinManagerXOrderService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ErrandService errandService;
    @Autowired
    private FreightService freightService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private OrderLocationManyService orderLocationManyService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ZhuanxianService zhuanxianService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private SuperviceService superviceService;

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add(HttpSession session) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("zhuan")) {
            ModelAndView mv = new ModelAndView();

            Subject currentUser = SecurityUtils.getSubject();
            Principal principal = (Principal) currentUser.getPrincipal();

            Company company = companyService.findOne(principal.getCompanyId());

            mv.addObject("companyId", company.getId());
            mv.addObject("companys", companyService.findAll());
            mv.addObject("weixinManagers", weixinManagerService.findByCompany(company.getId()));
            mv.addObject("address", company.getCityName());
            mv.addObject("initDate", new Date(System.currentTimeMillis() + 7200000));
            ServiceSetting checkOpen = ServiceUtil.checkOpen();
            if (checkOpen.isZhuanxian()) {
                List<Line> lines = null;
                if (principal.isCompanyType()) {
                    lines = zhuanxianService.queryLines(null);
                } else {
                    lines = zhuanxianService.queryLines(principal.getCompanyId());
                }
                mv.addObject("lines", lines);
            }
            mv.addObject("default", "zhuan");
            mv.addObject("mainCompany", String.valueOf(principal.isCompanyType()));

            List<CarType> carTypes = zhuancheService.queryCarTypeV4up(principal.getCompanyId());
            mv.addObject("carTypes", carTypes);
            mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME,
                CSRFTokenManager.getTokenForSession(session));
            mv.setViewName("order/add");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    // 追加
    @RequestMapping(value = "addmore/{id}", method = RequestMethod.GET)
    public ModelAndView addmore(HttpSession session, @PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuan")) {
            ModelAndView mv = new ModelAndView();

            Order order = zhuancheService.findOne(id);
            Company company = companyService.findOne(order.getCompanyId());
            mv.addObject("companyId", order.getCompanyId());
            mv.addObject("companys", companyService.findAll());
            List<CarType> carTypes;
            if (principal.isCompanyType() && principal.getCompanyId()
                .equals(order.getCompanyId())) {
                carTypes = zhuancheService.queryCarTypeV4up(null);
            } else {
                carTypes = zhuancheService.queryCarTypeV4up(order.getCompanyId());
            }
            mv.addObject("weixinManagers", weixinManagerService.findByCompany(company.getId()));
            mv.addObject("carTypes", carTypes);
            mv.addObject("lng", order.getStartLng());
            mv.addObject("lat", order.getStartLat());
            if (order.getServerTime().before(new Date())) {
                order.setServerTime(new Date());
            }
            mv.addObject("zhuanOrder", order);

            WeixinManagerXOrder weixinManagerXOrder = weixinManagerXOrderService.findByOrderId(id);
            if (null != weixinManagerXOrder) {
                mv.addObject("weixinManagerId", weixinManagerXOrder.getManagerId());
            }

            mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME,
                CSRFTokenManager.getTokenForSession(session));
            mv.addObject("initDate", new Date(System.currentTimeMillis() + 7200000));
            mv.addObject("default", "zhuan");
            mv.addObject("mainCompany", String.valueOf(principal.isCompanyType()));
            mv.setViewName("order/addmore");

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping("orderlist")
    public ModelAndView orderlist() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuan")) {
            ModelAndView mv = new ModelAndView();
            Company company = companyService.findOne(principal.getCompanyId());
            mv.addObject("lng", company.getLongitude());
            mv.addObject("lat", company.getLatitude());
            List<CarType> carTypes = null;
            if (principal.isCompanyType()) {
                carTypes = zhuancheService.queryCarTypes(null);
                mv.addObject("companys", companyService.findAll());
            } else {
                carTypes = zhuancheService.queryCarTypes(principal.getCompanyId());
            }
            mv.addObject("carTypes", carTypes);
            mv.setViewName("zhuanche/orderlist");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("orderlistData")
    public @ResponseBody
    Page<Map<String, Object>> orderListData(
        @RequestParam(required = false, value = "orderNumber") String orderNumber,
        @RequestParam(required = false, value = "clientPhone") String clientPhone,
        @RequestParam(required = false, value = "driverPhone") String driverPhone,
        @RequestParam(required = false, value = "companyName") String companyName,
        @RequestParam(required = false, value = "createOrderName") String createOrderName,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "orderType") String[] orderType,
        @RequestParam(required = false, value = "status") Integer[] status,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam(required = false, value = "treatment") String treatment,
        @RequestParam(required = false, value = "startFinishTime") String startFinishTime,
        @RequestParam(required = false, value = "endFinishTime") String endFinishTime)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuan")) {
            String allstatus = "";
            String allorderType = "";
            if (orderType != null) {
                for (int i = 0; i < orderType.length; i++) {
                    allorderType += orderType[i];
                    if (i != orderType.length - 1) {
                        allorderType += ",";
                    }
                }
            }
            if (status != null) {
                for (int i = 0; i < status.length; i++) {
                    allstatus += status[i];
                    if (i != status.length - 1) {
                        allstatus += ",";
                    }
                }
            }
            page = Pager.getPage();
            rows = Pager.getLimit();

            Page<Map<String, Object>> result = null;
            if (principal.isCompanyType()) {
                result = zhuancheService
                    .orderListData(orderNumber, clientPhone, driverPhone, companyName,
                        createOrderName, startTime, endTime, allorderType, allstatus, page, rows,
                        treatment,
                        startFinishTime, endFinishTime);
            } else {
                result = zhuancheService.orderListData(orderNumber, clientPhone, driverPhone, null,
                    createOrderName, startTime, endTime, allorderType, allstatus, page, rows,
                    treatment,
                    startFinishTime, endFinishTime);
            }

            return result;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "exportOrder", method = RequestMethod.GET)
    public @ResponseBody
    String exportOrder(
        @RequestParam(required = false, value = "orderNumber") String orderNumber,
        @RequestParam(required = false, value = "clientPhone") String clientPhone,
        @RequestParam(required = false, value = "driverPhone") String driverPhone,
        @RequestParam(required = false, value = "companyName") String companyName,
        @RequestParam(required = false, value = "createOrderName") String createOrderName,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "orderType") String[] orderType,
        @RequestParam(required = false, value = "status") Integer[] status,
        @RequestParam(required = false, value = "treatment") String treatment,
        @RequestParam(required = false, value = "startFinishTime") String startFinishTime,
        @RequestParam(required = false, value = "endFinishTime") String endFinishTime,
        HttpServletRequest req, HttpServletResponse response, HttpSession session)
        throws IOException, ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuan")) {

            String allstatus = "";
            String allorderType = "";
            if (orderType != null) {
                for (int i = 0; i < orderType.length; i++) {
                    allorderType += orderType[i];
                    if (i != orderType.length - 1) {
                        allorderType += ",";
                    }
                }
            }
            if (status != null) {
                for (int i = 0; i < status.length; i++) {
                    allstatus += status[i];
                    if (i != status.length - 1) {
                        allstatus += ",";
                    }
                }
            }
            List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
            if (principal.isCompanyType()) {
                content = zhuancheService.orderListDataExport(session, orderNumber, clientPhone,
                    driverPhone, companyName, createOrderName, startTime, endTime, allorderType,
                    allstatus,
                    treatment, startFinishTime, endFinishTime);
            } else {
                content = zhuancheService.orderListDataExport(session, orderNumber, clientPhone,
                    driverPhone, null, createOrderName, startTime, endTime, allorderType, allstatus,
                    treatment, startFinishTime, endFinishTime);
            }

            List<List<String>> rowlist = new ArrayList<List<String>>();
            String[] head = new String[27];
            head[0] = ("状态");
            head[1] = ("单号");
            head[2] = ("下单时间");
            head[3] = ("来源");
            head[4] = ("下单人");
            head[5] = ("客户名称");
            head[6] = ("客户电话");
            head[7] = ("使用人电话");
            head[8] = ("预约时间");
            head[9] = ("预约地");
            head[10] = ("目的地");
            head[11] = ("所属公司");
            head[12] = ("实收金额");
            head[13] = ("支付方式");
            head[14] = ("预算金额");
            head[15] = ("加收金额");
            head[16] = ("服务人员调价");

            head[17] = ("服务人员名称");
            head[18] = ("服务人员电话");

            head[19] = ("车辆类型");
            head[20] = ("租用类型");
            head[21] = ("车牌号");
            head[22] = ("服务时间");
            head[23] = ("里程");
            head[24] = ("等待时间");

            head[25] = ("备注");
            head[26] = ("销单原因");

            for (Map<String, Object> map : content) {
                List<String> celllist = new ArrayList<String>();
                if (map.get("status").equals(Order.ORDER_STATUS_NEW)) {
                    celllist.add("未派单");
                } else if (map.get("status").equals(Order.ORDER_STATUS_PAIDAN)) {
                    celllist.add("已派单");
                } else if (map.get("status").equals(Order.ORDER_STATUS_JIEDAN)
                    || map.get("status").equals(Order.ORDER_STATUS_ARRIVE)
                    || map.get("status").equals(Order.ORDER_STATUS_ZHIXING)) {
                    celllist.add("已接单");
                } else if (map.get("status").equals(Order.ORDER_STATUS_OK)) {
                    celllist.add("已完成");
                } else if (map.get("status").equals(Order.ORDER_STATUS_ARRIVE_DISTANCE)) {
                    celllist.add("已到达");
                } else if (map.get("status").equals(Order.ORDER_STATUS_XIAODAN)) {
                    celllist.add("已销单");
                }

                celllist.add(map.get("orderNo").toString());
                celllist.add(map.get("created").toString());
                celllist.add(map.get("channelName").toString());
                if (map.get("createOrderName") != null) {
                    celllist.add(map.get("createOrderName").toString());
                } else {
                    celllist.add("-");
                }
                celllist.add(map.get("passengerName").toString());
                celllist.add(UseAllDataUtil.useAllData(map.get("passengerPhone").toString()));
                celllist.add(map.get("showPhone").toString());
                celllist.add(map.get("serverTime").toString());

                if (map.get("startAddress") != null && map.get("startAddressDetail") != null) {
                    celllist.add(map.get("startAddress").toString() + "("
                        + map.get("startAddressDetail").toString() + ")");
                } else if (map.get("startAddress") == null
                    && map.get("startAddressDetail") != null) {
                    celllist.add("(" + map.get("startAddressDetail").toString() + ")");
                } else if (map.get("startAddress") != null
                    && map.get("startAddressDetail") == null) {
                    celllist.add(map.get("startAddress").toString());
                } else {
                    celllist.add("");
                }
                if (map.get("endAddress") != null && map.get("endAddressDetail") != null) {
                    celllist.add(map.get("endAddress").toString() + "("
                        + map.get("endAddressDetail").toString() + ")");
                } else if (map.get("endAddress") == null && map.get("endAddressDetail") != null) {
                    celllist.add("(" + map.get("endAddressDetail").toString() + ")");
                } else if (map.get("endAddress") != null && map.get("endAddressDetail") == null) {
                    celllist.add(map.get("endAddress").toString());
                } else {
                    celllist.add("");
                }

                celllist.add(map.get("companyName").toString());

                if (map.get("status").equals(Order.ORDER_STATUS_OK)) {
                    celllist.add(
                        map.get("realPay") == null ? "0元" : map.get("realPay").toString() + "元");
                    celllist.add(
                        map.get("preAndAfterPayType") == null ? "-" : map.get("preAndAfterPayType")
                            .toString());
                } else {
                    celllist.add("-");
                    celllist.add("-");
                }
                celllist.add(
                    map.get("budgetPay") == null ? "0元" : map.get("budgetPay").toString() + "元");
                if (map.get("status").equals(Order.ORDER_STATUS_OK)) {
                    celllist.add(("过路费：" + map.get("guoluMoney").toString() + "元，远程费："
                        + map.get("yuanchengMoney").toString() + "元，其他费：" + map.get("otherMoney")
                        .toString())
                        + "元");
                } else {
                    celllist.add("-");
                }
                celllist.add(
                    (null != map.get("justKilometres") ? map.get("justKilometres") + "公里，" : "-，")
                        + (null != map.get("justMoney") ? map.get("justMoney") + "元" : "-"));
                if (map.get("employName") != null) {
                    celllist.add(map.get("employName").toString());
                } else {
                    celllist.add("-");
                }
                if (map.get("employPhone") != null) {
                    celllist
                        .add(UseAllDataUtil.useAllDataDriver(map.get("employPhone").toString()));
                } else {
                    celllist.add("-");
                }

                celllist.add(map.get("carTypeName").toString());
                celllist.add(map.get("serviceType").toString());
                if (map.get("carNumber") != null) {
                    celllist.add(map.get("carNumber").toString());
                } else {
                    celllist.add("-");
                }

                if (map.get("runtime") != null) {
                    celllist.add(map.get("runtime").toString() + "分钟");
                } else {
                    celllist.add("0分钟");
                }
                celllist
                    .add(map.get("mileage") == null ? "0公里" : map.get("mileage").toString() + "公里");
                celllist
                    .add(map.get("midwayWait") == null ? "0分钟" : map.get("midwayWait").toString()
                        + "分钟");

                celllist.add(map.get("memoStr") == null ? "-" : map.get("memoStr").toString());
                if (map.get("cancelCause") != null) {
                    celllist.add(map.get("cancelCause").toString());
                } else {
                    celllist.add("-");
                }

                rowlist.add(celllist);
            }

            return ExcelUtil.createExcel(req, response, head, rowlist);
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "exportOrderProcess", method = RequestMethod.GET)
    public @ResponseBody
    Object exportOrderProcess(HttpSession session) {
        return session.getAttribute("exportZhuancheProcess");
    }

    @RequestMapping(value = "orders", method = RequestMethod.GET)
    public ModelAndView list(@RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "orderNo") String orderNo,
        @RequestParam(required = false, value = "employName") String employName,
        @RequestParam(required = false, value = "passengerName") String passengerName,
        @RequestParam(required = false, value = "carNumber") String carNumber,
        @RequestParam(required = false, value = "status") Integer status) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuan")) {
            Page<Order> page = zhuancheService.queryZhuanOrder(companyId, orderNo, null, employName,
                null, passengerName, null, carNumber, status);
            ModelAndView mv = new ModelAndView();
            mv.addObject("page", page);
            List<CarType> carTypes = zhuancheService.queryCarTypes(companyId);
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
                carTypes = zhuancheService.queryCarTypes(null);
            } else {
                carTypes = zhuancheService.queryCarTypes(principal.getCompanyId());
            }
            mv.addObject("carTypes", carTypes);
            mv.addObject("companyId", companyId);
            mv.addObject("orderNo", orderNo);
            mv.addObject("employName", employName);
            mv.addObject("passengerName", passengerName);
            mv.addObject("carNumber", carNumber);
            mv.addObject("status", status);
            Company company = companyService.findOne(principal.getCompanyId());
            mv.addObject("lng", company.getLongitude());
            mv.addObject("lat", company.getLatitude());
            mv.setViewName("zhuanche/order");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    // 备注
    @RequestMapping(value = "remark", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> remark(Long id,
        @RequestParam(required = false, value = "memo") String memo) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuan")) {
            Map<String, Object> result = new HashMap<String, Object>();
            Order order = zhuancheService.findOne(id);
            if (order != null) {
                try {
                    zhuancheService.remark(id, memo);
                    result.put("success", true);
                    result.put("message", "备注成功");
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "备注失败");
                }

            } else {
                result.put("success", false);
                result.put("message", "订单不存在");
            }
            return result;
        } else {
            throw new NoPermissionException();
        }
    }

    // 订单详情
    @RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
    public ModelAndView detail(@PathVariable("id") Long id) {
        ModelAndView mv = new ModelAndView();

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("zhuan")) {

            Order order = zhuancheService.findOne(id);
            // 获取用户所属公司id
            Long companyId = principal.getCompanyId();
            if (null != order) {
                if (principal.isCompanyType() || order.getCompanyId()
                    == companyId) {// 判定用户是和订单的companyId是否一致，一致才有权看订单信息，否则无权限
                    order.setEmployPhone(UseAllDataUtil.useAllDataDriver(order.getEmployPhone()));
                    order.setShowPhone(UseAllDataUtil.useAllData(order.getShowPhone()));
                    order.setPassengerPhone(UseAllDataUtil.useAllData(order.getPassengerPhone()));

                    String serviceTypeStr = "立即用车";
                    com.ybkj.daijia.server.zhuan.Order.ServiceType serviceType = order
                        .getServiceType();
                    if (null != serviceType) {
                        if (serviceType.compareTo(Order.ServiceType.tangzu) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000)
                                .after(order.getServerTime())) {// 一小时内立即,一小时外预约用车
                                serviceTypeStr = "立即用车";
                            } else {
                                serviceTypeStr = "预约用车";
                            }
                        }
                        if (serviceType.compareTo(Order.ServiceType.rizu) == 0) {
                            serviceTypeStr = "日租";
                        }
                        if (serviceType.compareTo(Order.ServiceType.banrizu) == 0) {
                            serviceTypeStr = "半日租";
                        }
                        if (serviceType.compareTo(Order.ServiceType.jieji) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000)
                                .after(order.getServerTime())) {
                                serviceTypeStr = "立即接机";
                            } else {
                                serviceTypeStr = "预约接机";
                            }
                        }
                        if (serviceType.compareTo(Order.ServiceType.songji) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000)
                                .after(order.getServerTime())) {
                                serviceTypeStr = "立即送机";
                            } else {
                                serviceTypeStr = "预约送机";
                            }
                        }
                        if (serviceType.compareTo(Order.ServiceType.jiezhan) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000)
                                .after(order.getServerTime())) {
                                serviceTypeStr = "立即接站";
                            } else {
                                serviceTypeStr = "预约接站";
                            }
                        }
                        if (serviceType.compareTo(Order.ServiceType.songzhan) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000)
                                .after(order.getServerTime())) {
                                serviceTypeStr = "立即送站";
                            } else {
                                serviceTypeStr = "预约送站";
                            }
                        }
                    }

                    // //////////////////////////////////////////////微信V5新加////////////////////////////////////////////////////

                    // 过滤评价标签
                    OrderReview review = order.getOrderReview();
                    if (null != review) {
                        String reviewContent = review.getContent(); // 评价内容
                        String subText = "&*&"; // 这是标签与评价内容的分隔符
                        String tagText = "&|&"; // 这是标签的分隔符
                        String realReview = null;
                        if (null != reviewContent) {

                            // 用户输入的评价，过滤掉了标签
                            String realContent = null; // 评价
                            String realTag = null;
                            if (reviewContent.contains(subText)) {
                                realContent = reviewContent
                                    .substring(reviewContent.lastIndexOf(subText) + 3,
                                        reviewContent.length());
                                realTag = reviewContent
                                    .substring(0, reviewContent.lastIndexOf(subText));
                            } else if (reviewContent.contains(tagText)) {
                                realTag = reviewContent;
                                realContent = "";
                            } else {
                                realContent = reviewContent;
                            }

                            // 没有标签，没有评价
                            if (null == realTag && (null == realContent || realContent.isEmpty())) {
                                realReview = "";
                            }

                            // 有标签，没有评价/有评价，将标签变为【标签】的形式
                            if (null != realTag) {
                                String[] tags = realTag.split(tagText);
                                StringBuffer bf = new StringBuffer();
                                for (String tag : tags) {
                                    if ("|".equals(tag)) {
                                        continue;
                                    }
                                    if (null != tag && !tag.isEmpty()) {
                                        bf.append("【" + tag + "】 ");
                                    }
                                }
                                realReview = (bf.toString() + realContent);
                            }

                            // 没有标签，有评价
                            if (null == realTag && null != realContent) {
                                realReview = realContent;
                            }
                        }
                        review.setContent(realReview);
                        order.setOrderReview(review);
                    }

                    // //////////////////////////////////////////////////////////////////////////////////////////////////

                    mv.addObject("order", order);
                    mv.addObject("serviceTypeStr", serviceTypeStr);
                    mv.addObject("treatment", order.isTreatment());
                    mv.addObject("cancel", order.getStatus().intValue() == 6 ? true : false);

                    List<OrderStatus> list = order.getStatusList();

                    SimpleDateFormat formart = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
                    mv.addObject("createDate", formart.format(order.getCreated()));

                    for (OrderStatus orderStatus : list) {
                        if (order.getStatus() != 6) {
                            if (orderStatus.getStatus() == 2) {// 接单记录
                                mv.addObject("jiedanDate",
                                    formart.format(orderStatus.getCreated()));
                            }
                            if (orderStatus.getStatus() == 4) {// 开始服务记录
                                mv.addObject("runDate", formart.format(orderStatus.getCreated()));
                            }
                            if (orderStatus.getStatus() == 4 && order.isTreatment()) {// 确认费用时间
                                mv.addObject("treatmentDate",
                                    formart.format(
                                        order.getTreatmentDate() != null ? order.getTreatmentDate()
                                            : orderStatus.getCreated()));
                            }
                            if (orderStatus.getStatus() == 5) {
                                mv.addObject("finishDate",
                                    formart.format(order.getFinishTime() != null ? order
                                        .getFinishTime() : orderStatus.getCreated()));
                            }
                        } else {
                            if (orderStatus.getStatus() == 2) {// 接单记录
                                mv.addObject("jiedanDate",
                                    formart.format(orderStatus.getCreated()));
                            }
                            if (orderStatus.getStatus() == 3
                                || orderStatus.getStatus() == 4) {// 开始服务记录
                                mv.addObject("runDate", formart.format(orderStatus.getCreated()));
                            }
                        }
                    }
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getStatus() == 6) {
                            order.setStatus(list.get(i - 1).getStatus());
                        }
                    }
                    mv.addObject("username", principal.getUsername());
                    mv.setViewName("zhuanche/detail");
                    return mv;
                } else {
                    throw new NoPermissionException();
                }
            }
        } else {
            throw new NoPermissionException();
        }
        return mv;
    }

    // 跳转手动完工界面
    @RequestMapping(value = "complete/{id}", method = RequestMethod.GET)
    public ModelAndView complete(HttpSession session, @PathVariable("id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuancheComplete")) {
            ModelAndView mv = new ModelAndView();
            Order order = zhuancheService.findOne(id);
            mv.addObject("order", order);
            mv.addObject("passenger", memberService.findOnePassenger(order.getPassengerId()));

            mv.setViewName("zhuanche/complete");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    // 后台完工
//  @RequestMapping(value = "completeOrder", method = RequestMethod.POST)
//  public synchronized @ResponseBody Result<Order> completeOrder(Long orderId, Integer midwayWait,
//      Integer runTime, Double mileage, String finishTime, String payType, String endAddress,
//      Double realPay, Double baoxiaoMoney, String employMemo, String baoxiaoMemo,
//      String prePayTypeDetail, Double guoluMoney, Long couponId, Long companyId) {
//    Subject subject = SecurityUtils.getSubject();
//    Principal principal = (Principal) subject.getPrincipal();
//
//    Result<Order> result = new Result<Order>();
//    result.setSuccess(false);
//
//    if (subject.isPermitted("zhuancheComplete")) {
//      Order dbOrder = zhuancheService.findOne(orderId);
//      if (dbOrder.getStatus().equals(Order.ORDER_STATUS_PAIDAN)
//          || dbOrder.getStatus().equals(Order.ORDER_STATUS_JIEDAN)
//          || dbOrder.getStatus().equals(Order.ORDER_STATUS_ARRIVE)
//          || dbOrder.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
//
//        if (dbOrder.isTreatment()) {
//          result.setMessage("订单已确认，不能手动完工");
//          return result;
//        }
//
//        Passenger passenger = memberService.findOnePassenger(dbOrder.getPassengerId());
//        if (null != passenger) {
//          if (PayType.sign.compareTo(Enum.valueOf(PayType.class, payType)) == 0) {
//            if (!passenger.isAllowOverdraw()) {
//              result.setMessage("该客户不能签单");
//              return result;
//            }
//          } else if (PayType.balance.compareTo(Enum.valueOf(PayType.class, payType)) == 0) {
//            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
//              if (passenger.getDrawMoney().doubleValue() < realPay.doubleValue()) {
//                result.setMessage("余额不足");
//                return result;
//              }
//            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
//              Enterprise enterprise = memberService.findOneEnterprise(passenger.getEnterprise_id());
//              if (enterprise.getDrawMoney().doubleValue() < realPay.doubleValue()) {
//                result.setMessage("余额不足");
//                return result;
//              }
//            }
//          }
//        }
//
//        if (PayType.cash.compareTo(Enum.valueOf(PayType.class, payType)) == 0) {// 代付
//          Long total = driverService.countById(dbOrder.getEmployId());
//          if (total != 1) {
//            result.setMessage("订单服务人员不存在，无法代付");
//            return result;
//          }
//        }
//
//        BigDecimal hasPayed = BigDecimal.ZERO;// 之前已经实际支付的钱
//
//        if (null == dbOrder.getCashMoney()) {
//          dbOrder.setCashMoney(BigDecimal.ZERO);
//        }
//
//        if (null == dbOrder.getSignMoney()) {
//          dbOrder.setSignMoney(BigDecimal.ZERO);
//        } else {
//          hasPayed = hasPayed.add(dbOrder.getSignMoney());
//        }
//
//        if (null == dbOrder.getBalanceMoney()) {
//          dbOrder.setBalanceMoney(BigDecimal.ZERO);
//        } else {
//          hasPayed = hasPayed.add(dbOrder.getBalanceMoney());
//        }
//
//        if (null == dbOrder.getAlipayMoney()) {
//          dbOrder.setAlipayMoney(BigDecimal.ZERO);
//        } else {
//          hasPayed = hasPayed.add(dbOrder.getAlipayMoney());
//        }
//
//        if (null == dbOrder.getWeixinMoney()) {
//          dbOrder.setWeixinMoney(BigDecimal.ZERO);
//        } else {
//          hasPayed = hasPayed.add(dbOrder.getWeixinMoney());
//        }
//
//        Coupon coupon = null;
//        BigDecimal coupon_hasPayed = BigDecimal.ZERO;
//        Double discount = null;
//        if (null != couponId) {
//          coupon = couponService.findOne(couponId);
//          if (null != coupon) {
//            if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
//              coupon_hasPayed = coupon.getCouponRule().getMoney();
//            } else if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DISCOUNT)) {
//              discount = coupon.getCouponRule().getDiscount();
//              coupon_hasPayed = new BigDecimal(realPay)
//                  .subtract(new BigDecimal(guoluMoney))
//                  .multiply(
//                      new BigDecimal(1).subtract(new BigDecimal(discount)
//                          .divide(new BigDecimal(10)))).setScale(0, BigDecimal.ROUND_DOWN);
//            }
//          }
//        }
//        dbOrder.setCouponMoney(coupon_hasPayed);
//        if (coupon_hasPayed.doubleValue() > 0 && null == prePayTypeDetail) {
//          dbOrder.setPrePayTypeDetail(Order.PayTypeDetails.coupon);
//        }
//        dbOrder.setDiscount(discount);
//
//        dbOrder.setOperating(principal.getUsername());
//        dbOrder.setTreatment(true);
//        dbOrder.setTreatmentDate(new Date());
//        dbOrder.setMidwayWait(midwayWait);
//        dbOrder.setRunTime(runTime);
//        dbOrder.setMileage(mileage);
//        dbOrder.setGuoluMoney(new BigDecimal(guoluMoney));
//        try {
//          dbOrder.setFinishTime(DateUtils.parseDate(finishTime, "yyyy-MM-dd HH:mm"));
//        } catch (ParseException e1) {
//          dbOrder.setFinishTime(new Date());
//        }
//        dbOrder.setRealPay(realPay);
//        if (null == dbOrder.getBudgetPay()) {
//          dbOrder.setBudgetPay(realPay);
//        }
//        if (baoxiaoMoney != null) {
//          dbOrder.setBaoxiaoMoney(new BigDecimal(baoxiaoMoney));
//        }
//        dbOrder.setBaoxiaoMemo(baoxiaoMemo);// 报销说明
//
//        dbOrder.setEmployMemo(employMemo);// 订单备注
//
//        if (StringUtils.isNotBlank(endAddress) && !dbOrder.getHasToPlace()) {
//          dbOrder.setEndAddress(endAddress);
//          try {
//            Company company = companyService.findOne(companyId);
//
//            Result<Map<String, Double>> result_place = HttpClientUtil.getLngAndLatByPlace(
//                endAddress, company.getCityName());
//            if (result_place.isSuccess()) {
//              Map<String, Double> map = result_place.getResult();
//              Double toPlaceLongitude = map.get("lng");
//              Double toPlaceLatitude = map.get("lat");
//              if (null != toPlaceLongitude && null != toPlaceLatitude) {
//                dbOrder.setEndLng(toPlaceLongitude);
//                dbOrder.setEndLat(toPlaceLatitude);
//              }
//            }
//          } catch (Exception e) {
//            e.printStackTrace();
//          }
//        }
//
//        BigDecimal money = new BigDecimal(dbOrder.getRealPay()).subtract(hasPayed.add(dbOrder
//            .getCouponMoney()));// 还需支付的钱
//
//        Driver driver = driverService.findOne(dbOrder.getEmployId());
//
//        zhuancheService.confirmTaskV4(dbOrder, driver);
//
//        if (money.doubleValue() <= 0) {
//          // 直接结算
//          Result<Order> result_complete = zhuancheService.completeTaskNewV3(dbOrder, passenger,
//              driver, "clickComplete", payType, hasPayed, Boolean.FALSE);
//
//          if (result_complete.isSuccess()) {
//            String detail = "【%s】手动完工了订单【" + dbOrder.getOrderNo() + "】";
//            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
//            applicationEventMulticaster.multicastEvent(operationLogEvent);
//
//            // 完工事件给司机推送
//            OrderAdminCompleteEvent orderAdminCompleteEvent = new OrderAdminCompleteEvent(dbOrder);
//            applicationEventMulticaster.multicastEvent(orderAdminCompleteEvent);
//
//            result.setSuccess(true);
//            return result;
//          } else {
//            result.setMessage(result.getMessage());
//            return result;
//          }
//
//        } else {
//          String payTypeStr = "";
//          if ("cash".equals(payType)) {
//            payTypeStr = "helppay";
//            dbOrder.setAfterPayTypeDetail(PayTypeDetails.helppay);
//          } else if ("sign".equals(payType)) {
//            payTypeStr = "sign";
//            dbOrder.setAfterPayTypeDetail(PayTypeDetails.sign);
//          } else if ("balance".equals(payType)) {
//            payTypeStr = "balance";
//            dbOrder.setAfterPayTypeDetail(PayTypeDetails.balance);
//          }
//          Result<Order> result_complete = zhuancheService.completeTaskNewV3(dbOrder, passenger,
//              driver, "clickPay", payTypeStr, hasPayed, Boolean.FALSE);
//
//          if (result_complete.isSuccess()) {
//            String detail = "【%s】手动完工了订单【" + dbOrder.getOrderNo() + "】";
//            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
//            applicationEventMulticaster.multicastEvent(operationLogEvent);
//
//            // 完工事件
//            OrderAdminCompleteEvent orderAdminCompleteEvent = new OrderAdminCompleteEvent(dbOrder);
//            applicationEventMulticaster.multicastEvent(orderAdminCompleteEvent);
//
//            result.setSuccess(true);
//            return result;
//          } else {
//            result.setMessage(result.getMessage());
//            return result;
//          }
//        }
//
//      } else {
//        result.setMessage("当前订单状态不能完工");
//        return result;
//      }
//
//    } else {
//      result.setMessage("您没有该权限");
//      return result;
//    }
//
//  }

    // 修改订单金额
    @RequestMapping(value = "updateRealMoney", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<Order> updateRealMoney(Long id, BigDecimal couponMoney,
        BigDecimal cashMoney, BigDecimal signMoney, BigDecimal balanceMoney, BigDecimal alipayMoney,
        BigDecimal weixinMoney, String content, BigDecimal driverMoney, Integer driverPlusMinus,
        BigDecimal memberMoney, Integer memberPlusMinus,
        @RequestParam(required = false, value = "wxMoney") BigDecimal wxMoney,
        @RequestParam(required = false, value = "wxPlusMinus") Integer wxPlusMinus) {
        Result<Order> vo = new Result<Order>();

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("modifycash")) {

            if (null == driverMoney || null == memberMoney) {
                vo.setSuccess(false);
                vo.setMessage("无效的服务人员或客户金额");
                return vo;
            }
            if (null == driverPlusMinus || null == memberPlusMinus) {
                vo.setSuccess(false);
                vo.setMessage("未知金额标识");
                return vo;
            }
            Pattern pattern2 = Pattern.compile("^\\+?[0-9][0-9]*(\\.\\d{1,2})?$");
            Matcher match2 = pattern2.matcher(driverMoney.toString());
            Matcher match3 = pattern2.matcher(memberMoney.toString());
            if (match2.matches() == false || match3.matches() == false) {
                vo.setSuccess(false);
                vo.setMessage("无效的服务人员或客户金额，金额最多保留2位小数");
                return vo;
            }

            if (null != wxMoney) {
                Matcher match4 = pattern2.matcher(wxMoney.toString());
                if (match4.matches() == false) {
                    vo.setSuccess(false);
                    vo.setMessage("无效的微信金额，金额最多保留2位小数");
                    return vo;
                }
            }

            if (org.apache.commons.lang3.StringUtils.isBlank(content)) {
                vo.setSuccess(false);
                vo.setMessage("请填写修改原因");
                return vo;
            }

            if (driverPlusMinus != 0) {
                driverMoney = driverMoney.multiply(new BigDecimal(-1));
            }
            if (memberPlusMinus != 0) {
                memberMoney = memberMoney.multiply(new BigDecimal(-1));
            }
            if (null != wxPlusMinus) {
                if (wxPlusMinus != 0) {
                    wxMoney = wxMoney.multiply(new BigDecimal(-1));
                }
            }

            Order order = zhuancheService.findOne(id);

            String detail = "【%s】修改订单【" + order.getOrderNo() + "】金额，原金额：" + order.getRealPay();

            if (null != couponMoney) {
                detail += "，修改后优惠券金额：" + couponMoney;
            }
            if (null != cashMoney) {
                detail += "，修改后代付金额：" + cashMoney;
            }
            if (null != signMoney) {
                detail += "，修改后签单金额：" + signMoney;
            }
            if (null != balanceMoney) {
                detail += "，修改后余额金额：" + balanceMoney;
            }
            if (null != alipayMoney) {
                detail += "，修改后支付宝金额：" + alipayMoney;
            }
            if (null != weixinMoney) {
                detail += "，修改后微信金额：" + weixinMoney;
            }

            detail += "，备注：" + content + "";

            vo = zhuancheService.updateRealMoney(order, couponMoney, cashMoney, signMoney, balanceMoney,
                alipayMoney, weixinMoney, driverMoney, memberMoney, wxMoney, content);

            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

        } else {
            vo.setSuccess(false);
            vo.setMessage("您没有该权限");
        }

        return vo;
    }

    // 追加
    @RequestMapping(value = "findByOrderId", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> findByOrderId(@RequestParam("id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuan")) {
            Map<String, Object> result = new HashMap<String, Object>();
            Order order = zhuancheService.findOne(id);
            result.put("order", order);
            return result;
        } else {
            throw new NoPermissionException();
        }
    }

    /**
     * 收回订单
     *
     * @param id
     * @param cause
     * @return
     */
    @RequestMapping(value = "callback", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> callback(Long id, String cause) {

        Map<String, Object> map = new HashMap<String, Object>();

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCallback")) {

            Order order = zhuancheService.findOne(id);

            if (order.getStatus().equals(Order.ORDER_STATUS_NEW)
                || order.getStatus().equals(Order.ORDER_STATUS_PAIDAN)
                || order.getStatus().equals(Order.ORDER_STATUS_JIEDAN)
                || order.getStatus().equals(Order.ORDER_STATUS_ARRIVE)) {

                if (order.isTreatment()) {
                    map.put("success", false);
                    map.put("message", "订单已确认，不能收回");
                    return map;
                }

                Result<Order> result = zhuancheService.callback(id, cause);
                Driver driver = driverService.findOne(order.getEmployId());
                map.put("success", false);
                if (result.isSuccess()) {
                    if (null != driver) {
                        if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                            driverService.updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                        }
                        ZhuanOrderCallBackEvent callBackEvent = new ZhuanOrderCallBackEvent(order, driver);
                        applicationEventMulticaster.multicastEvent(callBackEvent);
                    }
                    map.put("success", true);
                    return map;
                } else {
                    map.put("success", false);
                    map.put("message", result.getMessage());
                    return map;
                }
            } else {
                map.put("success", false);
                map.put("message", "当前订单状态不能回收");
                return map;
            }

        } else {
            map.put("success", false);
            map.put("message", "您没有该权限");
            return map;
        }
    }

    // 销单
    @RequestMapping(value = "cancel", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> cancel(@RequestParam("id") Long id,
        @RequestParam("cause") String cause) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Map<String, Object> map = new HashMap<String, Object>();

        if (subject.isPermitted("zhuan")) {

            Order order = zhuancheService.findOne(id);
            Result<Order> result = new Result<Order>();
            if (order.getStatus().equals(Order.ORDER_STATUS_NEW)
                || order.getStatus().equals(Order.ORDER_STATUS_PAIDAN)
                || order.getStatus().equals(Order.ORDER_STATUS_JIEDAN)
                || order.getStatus().equals(Order.ORDER_STATUS_ARRIVE)
                || order.getStatus().equals(Order.ORDER_STATUS_ARRIVE_DISTANCE)
                || order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {

                result = zhuancheService.cancelOrder(order, cause, principal.getUsername(), "adminCancel");
            } else {
                result.setSuccess(false);
                result.setMessage("订单已完成或已销单");
            }

            if (result.isSuccess()) {
                map.put("success", true);
                map.put("message", "销单成功");
            } else {
                map.put("success", false);
                map.put("message", result.getMessage());
            }
            return map;
        } else {
            map.put("success", false);
            map.put("message", "您没有该权限");
            return map;
        }
    }

    /**
     * 根据距离和时间按照公司的收费标准预估订单价格
     *
     * @param
     * @param companyId
     * @param time
     * @param mileage
     * @return
     */
    @RequestMapping(value = "getPrice", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> getPrice(@RequestParam("carTypeId") Long carTypeId,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam("time") String time, @RequestParam("passengerPhone") String passengerPhone,
        @RequestParam("serviceType") String serviceType, @RequestParam("mileage") String mileage) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuan")) {
            Map<String, Object> result = new HashMap<String, Object>();
            BigDecimal money = BigDecimal.ZERO;
            try {
                if (companyId == null || companyId == 0) {
                    Principal principal = (Principal) subject.getPrincipal();
                    companyId = principal.getCompanyId();
                }
                ServiceType type = zhuancheService.queryServiceType(carTypeId, companyId, serviceType);
                Area area = areaService.findOneWithCharge(type.getAreaId());
                Passenger passenger = memberService.findOnePassengerByPhone(passengerPhone);
                if (null != passenger) {
                    if (null != passenger.getGrade_id()) {
                        PassengerGrade passengerGrade = memberService.findOneGrade(passenger.getGrade_id());

                        if (null != passengerGrade) {

                            List<PassengerGradeAndArea> passengerGradeAndAreas = passengerGrade
                                .getPassengerGradeAndAreas();
                            PassengerGradeAndArea passengerGradeAndArea = null;
                            if (!CollectionUtils.isEmpty(passengerGradeAndAreas)) {
                                for (PassengerGradeAndArea pgaa : passengerGradeAndAreas) {
                                    if (carTypeId.equals(pgaa.getCarTypeId())) {
                                        passengerGradeAndArea = pgaa;
                                    }
                                }
                            }
                            if (Order.ServiceType.valueOf(serviceType).compareTo(Order.ServiceType.tangzu) == 0) {
                                if (null != passengerGradeAndArea && null != passengerGradeAndArea.getTzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGradeAndArea.getTzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                } else if (null != passengerGrade.getTzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGrade.getTzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                }
                            } else if (Order.ServiceType.valueOf(serviceType)
                                .compareTo(Order.ServiceType.banrizu) == 0) {
                                if (null != passengerGradeAndArea && null != passengerGradeAndArea.getBrzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGradeAndArea.getBrzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                } else if (null != passengerGrade.getBrzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGrade.getBrzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                }
                            } else if (Order.ServiceType.valueOf(serviceType).compareTo(Order.ServiceType.rizu) == 0) {
                                if (null != passengerGradeAndArea && null != passengerGradeAndArea.getRzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGradeAndArea.getRzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                } else if (null != passengerGrade.getRzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGrade.getRzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                }
                            } else if (Order.ServiceType.valueOf(serviceType).compareTo(Order.ServiceType.jieji) == 0) {
                                if (null != passengerGradeAndArea && null != passengerGradeAndArea.getJjAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGradeAndArea.getJjAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                } else if (null != passengerGrade.getJjAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGrade.getJjAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                }
                            } else if (Order.ServiceType.valueOf(serviceType).compareTo(Order.ServiceType.songji) == 0) {
                                if (null != passengerGradeAndArea && null != passengerGradeAndArea.getSjAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGradeAndArea.getSjAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                } else if (null != passengerGrade.getSjAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGrade.getSjAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                }
                            } else if (Order.ServiceType.valueOf(serviceType)
                                .compareTo(Order.ServiceType.jiezhan) == 0) {
                                if (null != passengerGradeAndArea && null != passengerGradeAndArea.getJzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGradeAndArea.getJzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                } else if (null != passengerGrade.getJzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGrade.getJzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                }
                            } else if (Order.ServiceType.valueOf(serviceType).compareTo(
                                Order.ServiceType.songzhan) == 0) {
                                if (null != passengerGradeAndArea && null != passengerGradeAndArea.getSzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGradeAndArea.getSzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                } else if (null != passengerGrade.getSzAreaId()) {
                                    Area one = areaService.findOneWithCharge(passengerGrade.getSzAreaId());
                                    if (one != null) {
                                        area = one;
                                    }
                                }
                            }
                        }
                    }
                }

                Long time1 = 0L;
                Double mileage1 = 0.0;
                if (time != null) {
                    Long day = 0L;
                    Long hour = 0L;
                    Long minute = 0L;
                    if (time.contains("天")) {
                        String str1 = time.substring(0, time.indexOf("天"));
                        day = Long.parseLong(str1);
                    }
                    if (time.contains("小时") && time.contains("天")) {
                        String str2 = time.substring(time.indexOf("天") + 1, time.indexOf("小时"));
                        hour = Long.parseLong(str2);
                    } else if (time.contains("小时") && !time.contains("天")) {
                        String str2 = time.substring(0, time.indexOf("小时"));
                        hour = Long.parseLong(str2);
                    }
                    if (time.contains("分钟") && time.contains("小时")) {
                        String str3 = time.substring(time.indexOf("小时") + 2, time.indexOf("分钟"));
                        minute = Long.parseLong(str3);
                    } else if (time.contains("分钟") && !time.contains("小时")) {
                        String str3 = time.substring(0, time.indexOf("分钟"));
                        minute = Long.parseLong(str3);
                    }
                    time1 = (day * 24 * 60) + (hour * 60) + (minute);

                }
                if (mileage != null) {
                    Double leng = 0.0;
                    if (mileage.contains("公里")) {
                        String str1 = mileage.substring(0, mileage.indexOf("公里"));
                        leng = Double.parseDouble(str1);
                    }
                    if (mileage.contains("米")) {
                        String str3 = mileage.substring(0, mileage.indexOf("米"));
                        leng = leng + (Double.parseDouble(str3) / 1000);
                    }
                    mileage1 = leng;
                }

//        SelectPrice selectPrice = new SelectPrice();
//        selectPrice.setPrice(time1, mileage1, area, new Date(),0D);
//
//        money = selectPrice.shouldCash;
//        BigDecimal startPrice = selectPrice.qbCost;
//        BigDecimal mileagePrice = selectPrice.disCost;
//        BigDecimal travelTimePrice = selectPrice.travalTimeCost;
//        ChargeStartTime price = selectPrice.getPrice();
//        StringBuilder builder = new StringBuilder();
//        builder.append("起步价:" + startPrice + "元\n");
//        List<ChargeStartDistance> distances = price.getChargeStartDistances();
//
//        if (distances != null && distances.size() != 0) {
//          for (ChargeStartDistance d : distances) {
//            builder.append(d.getStartdistance() + "公里到" + d.getDistance() + "公里内,加收" + d.getMoney()
//                + "元");
//            builder.append("\n");
//          }
//        }
//
//        builder.append("超过" + price.getQblc() + "公里");
//        builder.append("以后每" + price.getDjglUnit() + "公里");
//        builder.append("加收" + price.getDjglCost() + "元");
//        if (price.getDjglThresholdt() != 0) {
//          builder.append("(不足" + price.getDjglThresholdt() + "公里不计费)");
//        }
//        builder.append("\n");
//        builder.append("起步后" + price.getQbsj() + "分钟内不收费");
//        builder.append("以后每" + price.getDjsjUnit() + "分钟");
//        builder.append("加收" + price.getDjsjCost() + "元");
//        if (price.getDjsjThresholdt() != 0) {
//          builder.append("(不足" + price.getDjsjThresholdt() + "分钟不收费)");
//        }
//        builder.append("\n");
//        builder.append("免费等候" + price.getMfdhsj() + "分钟");
//        BigDecimal bigDecimal = price.getDhsjAtonceCost();
//
//        if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
//          builder.append("到达则立即加收" + price.getDhsjAtonceCost() + "元");
//        }
//        builder.append("后每" + price.getDhsjUnit() + "分钟");
//        builder.append("加收" + price.getDhsjCost() + "元");
//        if (price.getDhsjThresholdt() != 0) {
//          builder.append("(低于" + price.getDhsjThresholdt() + "分钟不计费)");
//        }
//        builder.append("\n");
//        if (StringUtils.isNotBlank(area.getMemo())) {
//          builder.append("备注:" + area.getMemo());
//        }
//        if (money != null) {
//          money = new BigDecimal(new DecimalFormat("0.0").format(money));
//        } else {
//          money = BigDecimal.ZERO;
//        }

                SelectPrice selectPrice = new SelectPrice();
                selectPrice.computePrice(-1, time1 * 60, 0L, mileage1, area, null);
                BigDecimal startPrice = selectPrice.getQbCost();
                BigDecimal mileagePrice = selectPrice.getDisCost();
                BigDecimal travelTimePrice = selectPrice.getTravalTimeCost();
                result.put("message", "请求成功");
                result.put("success", true);
                result.put("money", selectPrice.getShouldCash().doubleValue());
                result.put("travelTime", time1); // 执行时间
                result.put("startPrice", startPrice != null ? startPrice : 0.0); // 起步价
                result.put("mileage", mileage1 != null ? mileage1 : 0.0); // 行驶里程
                result.put("mileagePrice", mileagePrice != null ? mileagePrice : 0.0); // 行驶里程费用
                result.put("travelTimePrice", travelTimePrice != null ? travelTimePrice : 0.0); // 服务时间费用
                result.put("areaId", area.getId());
                return result;

            } catch (Exception e) {
                e.printStackTrace();
                result.put("success", false);
                result.put("message", "请求失败");
                return result;
            }

        } else {
            throw new NoPermissionException();
        }
    }

    // 获取附近服务人员
    @RequestMapping(value = "getEmployees", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getEmployees(
        @RequestParam("carTypeId") Long carTypeId, @RequestParam("startLat") Double startLat,
        @RequestParam("startLng") Double startLng, @RequestParam("serverTime") String serverTime,
        @RequestParam("limitLine") String limitLine) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuan")) {
            List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
            List<Car> list = zhuancheService.findByCarTypeId(carTypeId);
            // 判断车辆限行的星期几和serverTime的星期几
            Calendar calendar = Calendar.getInstance();
            int i = 0;
            if (StringUtils.isNotBlank(serverTime)) {
                Date date = DateUtils.parseDate(serverTime, "yyyy-MM-dd HH:mm");
                calendar.setTime(date);
                i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
                if (i == 0) {
                    i = 7;
                }
            }
            if (list != null && list.size() != 0) {
                for (Car car : list) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    Driver driver = driverService.findByCarId(car.getId());
                    if (limitLine.equals("true") && car.getLimitLine().equals(i)) {
                        continue;
                    }
                    if (driver != null && driver.getDriverJobType().contains("zhuanche")) {
                        if (driver.getStatus() != 1) {
                            continue;
                        }
                        Map<String, Object> map2 = getDriverBusy(driver.getId());
                        Boolean success = (Boolean) map2.get("success");
                        if (!success) {
                            continue;
                        }
                        try {
                            map.put("employId", driver.getId());
                            map.put("employName", driver.getRealname());
                            map.put("carNumber", car.getCarNumber());
                            DecimalFormat df = new DecimalFormat("#.00");
                            Double distance = Distance.doubleVal(startLat, startLng, driver.getLastLatitude(),
                                driver.getLastLongitude());
                            map.put("distance", Double.valueOf(df.format(distance)));
                            listMap.add(map);
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }

            }
            return listMap;
        } else {
            throw new NoPermissionException();
        }
    }

    /**
     * 后台直接创建专车订单
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> create(
        @RequestParam(required = false, value = "passengerId") Long passengerId,
        @RequestParam(required = false, value = "passengerName") String passengerName,
        @RequestParam("passengerPhone") String passengerPhone,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "companyName") String companyName,
        @RequestParam("startAddress") String startAddress,
        @RequestParam(required = false, value = "startAddressDetail") String startAddressDetail,
        @RequestParam("startLat") Double startLat, @RequestParam("startLng") Double startLng,
        @RequestParam(required = false, value = "endAddress") String endAddress,
        @RequestParam(required = false, value = "endAddressDetail") String endAddressDetail,
        @RequestParam(required = false, value = "endLat") Double endLat,
        @RequestParam(required = false, value = "endLng") Double endLng,
        @RequestParam("serverTime") String serverTime,
        @RequestParam("serviceType") String serviceType,
        @RequestParam("carTypes") String carTypes,
        @RequestParam(required = false, value = "memo") String memo,// 用车需求
        @RequestParam(required = false, value = "flightNo") String flightNo,// 航班号
        @RequestParam(required = false, value = "trainNo") String trainNo,// 车次号
        @RequestParam(required = false, value = "makePrice") BigDecimal makePrice,// 定价
        @RequestParam(required = false, value = "isMakePrice") Integer isMakePrice,// 是否定价
        @RequestParam("travelTime") Integer travelTime,// 预估时间
        @RequestParam("mileage") Double mileage,
        @RequestParam(required = false, value = "couponIds") String couponIds) throws ParseException {
        Map<String, Object> result = new HashMap<String, Object>();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (companyId == null || companyId == 0) {
            companyId = principal.getCompanyId();
        }
        if (makePrice == null) {
            makePrice = new BigDecimal(0);
        }
        if (StringUtils.isBlank(companyName)) {
            companyName = principal.getCompanyAbbreviation();
        }
        if (subject.isPermitted("zhuan")) {
            try {
                Integer bookStatus = 0;
                String channelName = Order.ORDER_TYPE_PHONE;

                Date serverDate = DateUtils.parseDate(serverTime, "yyyy-MM-dd HH:mm");
                Setting setting = settingUtils.get();
                Long bookTimeZhuan = setting.getBookTimeZhuan().longValue();
                // 计算是否是预约订单
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                // 去掉秒钟验证存在的问题
                Date nowDate = DateUtils.parseDate(df.format(new Date()), "yyyy-MM-dd HH:mm");
                Long book = serverDate.getTime() / 1000;
                Long now = nowDate.getTime() / 1000;
                Long compare = now + bookTimeZhuan * 60;
                if (compare <= book && bookTimeZhuan != 0) {
                    bookStatus = 1;
                }
                passengerPhone = passengerPhone.replaceAll(" ", "");
                passengerPhone = passengerPhone.replaceAll("-", "");
                Result<List<Order>> r = zhuancheService.createOrderV4up(passengerId, passengerName,
                    passengerPhone, companyId, companyName, startAddress, startAddressDetail, startLat,
                    startLng, endAddress, endAddressDetail, endLat, endLng, serverDate, carTypes,
                    couponIds, channelName, principal.getUsername(), serviceType, memo, flightNo, trainNo,
                    travelTime, mileage, principal.getUsername(), bookStatus, makePrice, isMakePrice);
                if (r.isSuccess()) {
                    result.put("success", true);
                    result.put("message", "下单成功!");

                    List<Order> orderList = r.getResult();
                    for (Order o : orderList) {

                        String detail = "【%s】新增专车订单【" + o.getOrderNo() + "】";
                        OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                        applicationEventMulticaster.multicastEvent(operationLogEvent);

                    }

                    if (null == passengerId) {
                        Passenger passenger = memberService.findOnePassengerByPhone(passengerPhone);
                        if (null != passenger) {
                            // 新注册活动
                            ReactorVo rVo = new ReactorVo();
                            rVo.setPassenger(passenger);
                            rVo.setActivityEvent(ActivityEvent.newRegister);
                            ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                            applicationEventMulticaster.multicastEvent(activityCheckEvent);
                        }
                    }

                } else {
                    result.put("success", false);
                    result.put("message", r.getMessage());
                }

            } catch (Exception e) {
                e.printStackTrace();
                result.put("success", false);
                result.put("message", "下单失败");
            }
            return result;

        } else {
            throw new NoPermissionException();
        }
    }

    // @RequestMapping(value = "create2", method = RequestMethod.POST)
    // public @ResponseBody Map<String, Object> create2(
    // @RequestParam(required=false,value="passengerId") Long passengerId,
    // @RequestParam(required=false,value="passengerName") String passengerName,
    // @RequestParam("passengerPhone") String passengerPhone,
    // @RequestParam(required=false,value="showPhone") String showPhone,
    // @RequestParam(required=false,value="companyId") Long companyId,
    // @RequestParam(required=false,value="companyName") String companyName,
    // @RequestParam("carTypeId") Long carTypeId,
    // @RequestParam("startAddress") String startAddress,
    // @RequestParam(required=false,value="startAddressDetail")String
    // startAddressDetail,
    // @RequestParam("startLat") Double startLat,
    // @RequestParam("startLng") Double startLng,
    // @RequestParam(required=false,value="endAddress") String endAddress,
    // @RequestParam(required=false,value="endAddressDetail")String
    // endAddressDetail,
    // @RequestParam(required=false,value="endLat") Double endLat,
    // @RequestParam(required=false,value="endLng") Double endLng,
    // @RequestParam("serverTime") String serverTime,
    // @RequestParam(required=false,value="budgetPay") Double budgetPay,
    // @RequestParam(required=false,value="startPrice")Double startPrice,
    // @RequestParam(required=false,value="mileagePrice")Double mileagePrice,
    // @RequestParam(required=false,value="runTimePrice")Double runTimePrice,
    // @RequestParam(required=false,value="travelTime")Integer travelTime,
    // @RequestParam(required=false,value="mileage")Double mileage,
    // @RequestParam(required = false, value = "employId")Long employId,
    // @RequestParam(required = false, value = "couponId")Long couponId) throws
    // ParseException{
    // Subject subject = SecurityUtils.getSubject();
    // Map<String, Object> result = new HashMap<String, Object>();
    // Principal principal = (Principal) subject.getPrincipal();
    // if(companyId==null || companyId==0){
    // companyId=principal.getCompanyId();
    // }
    // if(StringUtils.isBlank(companyName)){
    // companyName=principal.getCompanyName();
    // }
    // if (subject.isPermitted("zhuan")) {
    // String message="下单成功!";
    // try {
    // if(null!=employId){
    // Driver driver=driverService.findOne(employId);
    // if(!driver.getStatus().equals(Driver.DRIVER_ONLINE)){
    // employId=null;
    // message="下单成功,该服务人员状态非空闲,不能立即派单";
    // }
    // if(!driver.getDriverJobType().equals(Driver.DriverJobType.all)){
    // if(!driver.getDriverJobType().contains(Driver.DriverJobType.zhuanche.toString())){
    // employId=null;
    // message="下单成功,该服务人员不能派专车订单";
    // }
    // }
    // Map<String, Object> map = getDriverBusy(employId);
    // Boolean success=(Boolean)map.get("success");
    // if(!success){
    // employId=null;
    // Integer code=(Integer)map.get("code");
    // if(code==-1){
    // message="下单成功,该服务人员还有未完成的代驾工单,不能立即派单";
    // }else if(code==-2){
    // message="下单成功,该服务人员还有未完成的专车工单,不能立即派单";
    // }else if(code==-3){
    // message="下单成功,该服务人员还有未完成的跑腿工单,不能立即派单";
    // }
    // }
    // }
    // String channelName=Order.ORDER_TYPE_PHONE;
    //
    // Date serverDate = DateUtils.parseDate(serverTime, "yyyy-MM-dd HH:mm");
    // passengerPhone=passengerPhone.replaceAll(" ", "");
    // passengerPhone=passengerPhone.replaceAll("-", "");
    // Result<Order> r =zhuancheService.createOrder(
    // passengerId, passengerName, passengerPhone,passengerPhone, companyId,
    // companyName, carTypeId, startAddress, startAddressDetail,
    // startLat, startLng, endAddress, endAddressDetail, endLat, endLng,
    // serverDate, budgetPay, startPrice,
    // mileagePrice, runTimePrice, travelTime,
    // mileage,employId,channelName,couponId,principal.getUsername());
    //
    // if(r.isSuccess()){
    // result.put("success",true);
    // result.put("message", message);
    //
    // if(couponId!=null){
    // Coupon coupon = couponService.findOne(couponId);
    // coupon.setStatus(Coupon.COUPON_STATUS_HASUSED);
    // couponService.update(coupon);
    // }
    //
    // Order order=r.getResult();
    //
    // if(order!=null){
    // ZhuanOrderCreateEvent createEvent=new
    // ZhuanOrderCreateEvent(order.getId());
    // applicationEventMulticaster.multicastEvent(createEvent);
    //
    // ZhuanOrderRecordEvent orderRecordEvent = new
    // ZhuanOrderRecordEvent(order.getId());
    // applicationEventMulticaster.multicastEvent(orderRecordEvent);
    //
    // if(order.getStatus()==1){
    // String detail="【%s】派专车单【"+order.getOrderNo()+"】";
    // OperationLogEvent operationLogEvent = new
    // OperationLogEvent(principal,detail);
    // applicationEventMulticaster.multicastEvent(operationLogEvent);
    //
    // //派单事件
    // ZhuanOrderPaidanEvent paidanEvent = new
    // ZhuanOrderPaidanEvent(order.getId());
    // applicationEventMulticaster.multicastEvent(paidanEvent);
    // }
    // }
    // }else{
    // result.put("success",false);
    // result.put("message", r.getMessage());
    // }
    //
    // } catch (Exception e) {
    // result.put("success",false);
    // result.put("message", e.getMessage());
    // }
    //
    // return result;
    //
    // }else{
    // throw new NoPermissionException();
    // }
    // }
    @RequestMapping(value = "carsData", method = RequestMethod.GET)
    public @ResponseBody
    Page<Car> carsData(
        @RequestParam(required = false, value = "company") String companyNames,
        @RequestParam(required = false, value = "carType") String carTypes,
        @RequestParam(required = false, value = "carNumber") String carNumber,
        @RequestParam(required = false, value = "employName") String employName,
        @RequestParam(required = false, value = "status") Integer[] status,
        @RequestParam(required = false, value = "isPlatform") Integer[] isPlatform) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("zhuanCar")) {
            try {
                Principal principal = (Principal) subject.getPrincipal();
                String allstatus = "";
                if (status != null) {
                    for (int i = 0; i < status.length; i++) {
                        allstatus += status[i];
                        if (i != status.length - 1) {
                            allstatus += ",";
                        }
                    }
                }
                String isPlatforms = "";
                if (isPlatform != null) {
                    for (int i = 0; i < isPlatform.length; i++) {
                        isPlatforms += isPlatform[i];
                        if (i != isPlatform.length - 1) {
                            isPlatforms += ",";
                        }
                    }
                }
                Page<Car> page = null;
                if (principal.isCompanyType()) {
                    page = zhuancheService.queryByParamsCarsV4up(null, companyNames, carTypes, carNumber,
                        employName, allstatus, isPlatforms);
                } else {
                    page = zhuancheService.queryByParamsCarsV4up(principal.getCompanyId(), null, carTypes,
                        carNumber, employName, allstatus, isPlatforms);
                }

                return page;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        return null;
    }

    // 查询车辆列表
    @RequestMapping(value = "cars", method = RequestMethod.GET)
    public ModelAndView cars(HttpServletRequest req) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        ModelAndView mv = new ModelAndView();
        if (subject.isPermitted("zhuanCar")) {
            Principal principal = (Principal) subject.getPrincipal();
            List<CarType> carTypes = zhuancheService.queryCarTypeV4up(principal.getCompanyId());

            List<Company> companys = companyService.findAll();

            mv.addObject("companys", companys);
            mv.addObject("carTypes", carTypes);
            ServiceSetting serviceSetting = ServiceUtil.checkOpen();
            if (serviceSetting.isJgpt()) {
                mv.addObject("isUpPlatformInfo", settingUtils.get().isUpPlatformInfo());
            } else {
                mv.addObject("isUpPlatformInfo", false);
            }

            //等保 不能重复上传
            Long time_token = System.currentTimeMillis();
            //车辆照片
            req.getSession().setAttribute("upload_img_body_token", time_token);
//      mv.addObject("upload_img_body_token", time_token);
            //车牌照片
            req.getSession().setAttribute("upload_img_plate_token", time_token);
//      mv.addObject("upload_img_plate_token", time_token);

            mv.setViewName("zhuanche/car");
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "queryCarByNumber", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> queryCarByNumber(
        @RequestParam("carNumber") String carNumber, @RequestParam("flights") String flights)
        throws ParseException {
        Map<String, Object> map = new HashMap<String, Object>();

        if (!CarNumberUtils.isCarNumber(carNumber)) {
            map.put("code", 0);
            map.put("message", "车牌号码格式不正确!");
        } else {
            if (null != flights && !flights.equals("")) {
                Car car = zhuancheService.getCarByNumberAndFlights(carNumber, flights);
                try {
                    if (null != car) {
                        map.put("code", 0);
                        map.put("message", "车牌号已用");
                        map.put("data", car);
                    } else {
                        map.put("code", -1);
                    }
                } catch (Exception e) {
                    map.put("code", -1);
                }
            } else {
                Car car = zhuancheService.queryCarByNumber(carNumber);
                try {
                    if (null != car) {
                        map.put("code", 0);
                        map.put("message", "车牌号已用");
                        map.put("data", car);
                    } else {
                        map.put("code", -1);
                    }
                } catch (Exception e) {
                    map.put("code", -1);
                }
            }
        }
        return map;
    }

    // 保存车辆
    @RequestMapping(value = "createCar", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> createCar(Car car, String pictureAddress)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuanCar")) {
            if (StringUtils.isNotBlank(car.getCarNumber())) {
                car.setCarNumber(car.getCarNumber().toUpperCase());
            }
            if (!principal.isCompanyType()) {
                car.setCompanyId(principal.getCompanyId());
                car.setCompanyName(principal.getCompanyAbbreviation());
            }
            if (StringUtils.isNotBlank(pictureAddress)) {
                car.setPicture(pictureAddress);
            }
            return zhuancheService.createCar(car);
        } else {
            throw new NoPermissionException();
        }
    }

    // 根据昵称,工号,电话模糊查询服务人员
    @RequestMapping(value = "getDriver", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getDriver(
        @RequestParam(required = true, value = "param") String param,
        @RequestParam(required = false, value = "companyId") Long companyId) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        List<Driver> drivers = new ArrayList<Driver>();
        if (principal.isCompanyType()) {
            drivers = driverService.findByParamLike(param, companyId);
        } else {
            drivers = driverService.findByParamLike(param, principal.getCompanyId());
        }
        for (Driver driver : drivers) {
            if (driver.getDriverJobType().contains("zhuanche")) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", driver.getId());
                map.put("username", driver.getUsername());// 工号
                map.put("phone", driver.getPhone());// 电话
                list.add(map);
            }
        }
        return list;
    }

    // 查询单个车辆
    @RequestMapping(value = "queryCar", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> queryCar(@RequestParam("id") Long id)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuan")) {
            Map<String, Object> map = new HashMap<String, Object>();
            Car car = zhuancheService.findCar(id);
            List<Company> companys = companyService.findAll();
            Long companyId = car.getCompanyId();
            // if(!principal.isCompanyType()){
            // companyId=principal.getCompanyId();
            // }
            List<CarType> carTypes = zhuancheService.queryCarTypeV4up(companyId);
            if (car != null) {
                map.put("companys", companys);
                map.put("carTypes", carTypes);
                map.put("success", true);
                map.put("data", car);
                map.put(
                    "buyTime",
                    car.getBuyTime() == null ? null : new SimpleDateFormat("yyyy-MM-dd").format(car
                        .getBuyTime()));
                map.put("insuranceTime",
                    car.getInsuranceTime() == null ? null : new SimpleDateFormat(
                        "yyyy-MM-dd").format(car.getInsuranceTime()));
                map.put("overhaulTime", car.getOverhaulTime() == null ? null : new SimpleDateFormat(
                    "yyyy-MM-dd").format(car.getOverhaulTime()));
                if (car.getRegistrationTime() != null) {
                    map.put("registrationTime",
                        new SimpleDateFormat("yyyy-MM-dd").format(car.getRegistrationTime()));
                }
                if (car.getNextOverhaulTime() != null) {
                    map.put("nextOverhaulTime",
                        new SimpleDateFormat("yyyy-MM-dd").format(car.getNextOverhaulTime()));
                }
                if (car.getValidTime() != null) {
                    map.put("validTime",
                        new SimpleDateFormat("yyyy-MM-dd").format(car.getValidTime()));
                }
                if (car.getInvalidTime() != null) {
                    map.put("invalidTime",
                        new SimpleDateFormat("yyyy-MM-dd").format(car.getInvalidTime()));
                }
                if (car.getTaxiRegisterTime() != null) {
                    map.put("taxiRegisterTime",
                        new SimpleDateFormat("yyyy-MM-dd").format(car.getTaxiRegisterTime()));
                }
                if (car.getDeviceInstallTime() != null) {
                    map.put("deviceInstallTime",
                        new SimpleDateFormat("yyyy-MM-dd").format(car.getDeviceInstallTime()));
                }
                if (car.getInsValidTime() != null) {
                    map.put("insValidTime",
                        new SimpleDateFormat("yyyy-MM-dd").format(car.getInsValidTime()));
                }

            } else {
                map.put("success", false);
                map.put("message", "车辆删除失败");
            }
            return map;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 查询指定公司的专车车辆类型
     *
     * @param companyId
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "queryCarTypes", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> queryCarTypes(@RequestParam("companyId") Long companyId)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuan")) {
            Map<String, Object> map = new HashMap<String, Object>();
            if (!principal.isCompanyType()) {
                companyId = principal.getCompanyId();
            }
            List<CarType> carTypes = zhuancheService.queryCarTypeV4up(companyId);
            if (carTypes != null && carTypes.size() != 0) {
                map.put("carTypes", carTypes);
                map.put("arealist", areaService.listAll());
                map.put("success", true);
            } else {
                map.put("message", "该公司暂无车辆类型");
                map.put("success", false);
            }

            return map;
        } else {
            throw new NoPermissionException();
        }

    }

    // 删除车辆
    @RequestMapping(value = "deleteCar", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> deleteCar(@RequestParam("id") Long id, HttpServletRequest req)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuan")) {

            Map<String, Object> map = new HashMap<String, Object>();

            try {
                // 上传监管平台
                Car car = zhuancheService.findCar(id);
                car.setFlag(3);
                superviceService.ClbaMessage(car,
                    WebUtils.getRealPath(req.getSession().getServletContext(), "/"));
            } catch (FileNotFoundException e) {

                e.printStackTrace();
            }

            int i = zhuancheService.deleteCar(id);
            if (i == 1) {
                map.put("success", true);
                map.put("message", "车辆删除成功");

            } else {
                map.put("success", false);
                map.put("message", "车辆删除失败");
            }
            return map;
        } else {
            throw new NoPermissionException();
        }

    }

    // 查询车辆类型列表
    @RequestMapping(value = "carTypes", method = RequestMethod.GET)
    public ModelAndView carTypes() throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        ModelAndView mv = new ModelAndView();
        if (subject.isPermitted("zhuanCar")) {
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            }
            mv.addObject("companyId", principal.getCompanyId());
            mv.addObject("arealist", areaService.listAll());
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            } else {
                List<Company> list = new ArrayList<Company>();
                list.add(companyService.findOne(principal.getCompanyId()));
                mv.addObject("companys", list);
            }

            mv.addObject("arealist", areaService.listAll());
            mv.setViewName("zhuanche/carType");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    // 跳转车型关联公司界面
    @RequestMapping(value = "carTypeCompany/{id}", method = RequestMethod.GET)
    public ModelAndView carTypeCompany(@PathVariable("id") Long id,
        @RequestParam("carTypeName") String carTypeName) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        ModelAndView mv = new ModelAndView();
        if (subject.isPermitted("zhuanCar")) {
            mv.addObject("carTypeId", id);
            mv.addObject("carTypeName", carTypeName);
            Principal principal = (Principal) subject.getPrincipal();
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            } else {
                List<Company> list = new ArrayList<Company>();
                list.add(companyService.findOne(principal.getCompanyId()));
                mv.addObject("companys", list);
            }

            mv.addObject("arealist", areaService.listAll());
            mv.setViewName("zhuanche/carTypeCompany");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    // 删除车辆类型
    @RequestMapping(value = "deleteCarTypeV4up", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> deleteCarTypeV4up(@RequestParam("id") Long id)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            try {
                CarType carType = zhuancheService.findCarType(id);
                if (null != carType && carType.getTypeName().equals("出租车")) {
                    map.put("code", 500);
                    map.put("message", "出租车不能删除");
                } else {
                    map = zhuancheService.deleteCarTypeV4up(id);
                }
            } catch (Exception e) {
                map.put("code", 500);
                map.put("message", "车辆类型删除失败");
            }
            return map;
        } else {
            throw new NoPermissionException();
        }

    }

    // 保存车辆类型
    @RequestMapping(value = "createCarType", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> createCarType(@RequestParam("name") String name,
        @RequestParam("sequence") Integer sequence,
        @RequestParam(required = false, value = "ifTaxi") String ifTaxi,
        @RequestParam("accessibleType") String accessibleType,
        @RequestParam(required = false, value = "picture") String picture) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            map = zhuancheService.createCarType(name, sequence, picture, ifTaxi, accessibleType);
            return map;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "queryCarTypeV4up", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> queryCarTypeV4up() throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Page<CarType> page = zhuancheService.queryCarTypeV4up();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", page);
            map.put("areaList", areaService.listAll());
            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "queryCarTypeCompany", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> queryCarTypeCompany(
        @RequestParam(required = true, value = "carTypeId") Long carTypeId,
        @RequestParam(required = false, value = "companyName") String companyName,
        @RequestParam(required = false, value = "companyId") Long companyId) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            Page<CarTypeCompany> page = zhuancheService.queryCarTypeCompany(carTypeId, companyName,
                companyId);
            List<Area> areaList = areaService.listAll();

            // 当对应的收费标准删除时，列表中不应该显示
            List<CarTypeCompany> contents = page.getContent();
            for (CarTypeCompany carTypeCompany : contents) {
                boolean tanzuFlag = false;
                boolean rizuFlag = false;
                boolean banrizuFlag = false;
                boolean jiejiFlag = false;
                boolean songjiFlag = false;
                boolean jiezhanFlag = false;
                boolean songzhanFlag = false;
                // 如果遍历到立即tangzu收费标准还存在收费标准列表，终止循环,不改变值(flag=true)
                long tangzuAreaId = carTypeCompany.getTangzuAreaId();
                tanzuFlag = isAreaIdExist(areaList, carTypeCompany, tangzuAreaId, tanzuFlag);
                // rizu
                Long rizuAreaId = carTypeCompany.getRizuAreaId();
                rizuFlag = isAreaIdExist(areaList, carTypeCompany, rizuAreaId, rizuFlag);
                // banrizu
                Long banrizuAreaId = carTypeCompany.getBanrizuAreaId();
                banrizuFlag = isAreaIdExist(areaList, carTypeCompany, banrizuAreaId, banrizuFlag);
                // jieji
                Long jiejiAreaId = carTypeCompany.getJiejiAreaId();
                jiejiFlag = isAreaIdExist(areaList, carTypeCompany, jiejiAreaId, jiejiFlag);
                // songji
                Long songjiAreaId = carTypeCompany.getSongjiAreaId();
                songjiFlag = isAreaIdExist(areaList, carTypeCompany, songjiAreaId, songjiFlag);
                // jiezhan
                Long jiezhanAreaId = carTypeCompany.getJiezhanAreaId();
                jiezhanFlag = isAreaIdExist(areaList, carTypeCompany, jiezhanAreaId, jiezhanFlag);
                // songzhan
                Long songzhanAreaId = carTypeCompany.getSongzhanAreaId();
                songzhanFlag = isAreaIdExist(areaList, carTypeCompany, songzhanAreaId,
                    songzhanFlag);
                // 如果再收费标准列表中未发现tangzu收费标准(flage = false)，改变值
                if (!tanzuFlag) {
                    carTypeCompany.setTangzuAreaId(null);
                    carTypeCompany.setTangzuAreaName(null);
                }
                // rizu
                if (!rizuFlag) {
                    carTypeCompany.setRizuAreaId(null);
                    carTypeCompany.setRizuAreaName(null);
                }
                // banrizu
                if (!banrizuFlag) {
                    carTypeCompany.setBanrizuAreaId(null);
                    carTypeCompany.setBanrizuAreaName(null);
                }
                // jieji
                if (!jiejiFlag) {
                    carTypeCompany.setJiejiAreaId(null);
                    carTypeCompany.setJiejiAreaName(null);
                }
                // songji
                if (!songjiFlag) {
                    carTypeCompany.setSongjiAreaId(null);
                    carTypeCompany.setSongjiAreaName(null);
                }
                // jiezhan
                if (!jiezhanFlag) {
                    carTypeCompany.setJiezhanAreaId(null);
                    carTypeCompany.setJiezhanAreaName(null);
                }
                // songzhan
                if (!songzhanFlag) {
                    carTypeCompany.setSongzhanAreaId(null);
                    carTypeCompany.setSongzhanAreaName(null);
                }
            }

            map.put("page", page);
            map.put("areaList", areaList);

            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "startCarTypeCompany", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> startCarTypeCompany(
        @RequestParam(required = true, value = "carTypeId") Long carTypeId,
        @RequestParam(required = true, value = "companyId") Long companyId,
        @RequestParam(required = true, value = "companyName") String companyName,
        @RequestParam(required = true, value = "tangzuAreaId") Long tangzuAreaId,
        @RequestParam(required = true, value = "rizuAreaId") Long rizuAreaId,
        @RequestParam(required = true, value = "banrizuAreaId") Long banrizuAreaId,
        @RequestParam(required = true, value = "jiejiAreaId") Long jiejiAreaId,
        @RequestParam(required = true, value = "songjiAreaId") Long songjiAreaId,
        @RequestParam(required = true, value = "jiezhanAreaId") Long jiezhanAreaId,
        @RequestParam(required = true, value = "songzhanAreaId") Long songzhanAreaId,
        @RequestParam(required = true, value = "tangzuAreaName") String tangzuAreaName,
        @RequestParam(required = true, value = "rizuAreaName") String rizuAreaName,
        @RequestParam(required = true, value = "banrizuAreaName") String banrizuAreaName,
        @RequestParam(required = true, value = "jiejiAreaName") String jiejiAreaName,
        @RequestParam(required = true, value = "songjiAreaName") String songjiAreaName,
        @RequestParam(required = true, value = "jiezhanAreaName") String jiezhanAreaName,
        @RequestParam(required = true, value = "songzhanAreaName") String songzhanAreaName)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            map = zhuancheService
                .startCarTypeCompany(carTypeId, companyId, companyName, tangzuAreaId,
                    rizuAreaId, banrizuAreaId, jiejiAreaId, songjiAreaId, jiezhanAreaId,
                    songzhanAreaId,
                    tangzuAreaName, rizuAreaName, banrizuAreaName, jiejiAreaName, songjiAreaName,
                    jiezhanAreaName, songzhanAreaName);

            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "updateCarTypeCompany", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateCarTypeCompany(
        @RequestParam(required = true, value = "carTypeId") Long carTypeId,
        @RequestParam(required = true, value = "companyId") Long companyId,
        @RequestParam(required = true, value = "companyName") String companyName,
        @RequestParam(required = true, value = "tangzuAreaId") Long tangzuAreaId,
        @RequestParam(required = true, value = "rizuAreaId") Long rizuAreaId,
        @RequestParam(required = true, value = "banrizuAreaId") Long banrizuAreaId,
        @RequestParam(required = true, value = "jiejiAreaId") Long jiejiAreaId,
        @RequestParam(required = true, value = "songjiAreaId") Long songjiAreaId,
        @RequestParam(required = true, value = "jiezhanAreaId") Long jiezhanAreaId,
        @RequestParam(required = true, value = "songzhanAreaId") Long songzhanAreaId,
        @RequestParam(required = true, value = "tangzuAreaName") String tangzuAreaName,
        @RequestParam(required = true, value = "rizuAreaName") String rizuAreaName,
        @RequestParam(required = true, value = "banrizuAreaName") String banrizuAreaName,
        @RequestParam(required = true, value = "jiejiAreaName") String jiejiAreaName,
        @RequestParam(required = true, value = "songjiAreaName") String songjiAreaName,
        @RequestParam(required = true, value = "jiezhanAreaName") String jiezhanAreaName,
        @RequestParam(required = true, value = "songzhanAreaName") String songzhanAreaName)
        throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            map = zhuancheService
                .updateCarTypeCompany(carTypeId, companyId, companyName, tangzuAreaId,
                    rizuAreaId, banrizuAreaId, jiejiAreaId, songjiAreaId, jiezhanAreaId,
                    songzhanAreaId,
                    tangzuAreaName, rizuAreaName, banrizuAreaName, jiejiAreaName, songjiAreaName,
                    jiezhanAreaName, songzhanAreaName);

            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "deleteCarTypeCompany", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> deleteCarTypeCompany(
        @RequestParam("carTypeCompanyId") Long carTypeCompanyId) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            try {
                map = zhuancheService.deleteCarTypeCompany(carTypeCompanyId);
            } catch (Exception e) {
                map.put("code", 500);
                map.put("message", "公司车型取消失败");
            }
            return map;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "updateCarTypeV4up", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateCarTypeV4up(
        @RequestParam(required = true, value = "id") Long id,
        @RequestParam(required = true, value = "name") String name,
        @RequestParam(required = true, value = "sequence") Integer sequence,
        @RequestParam(required = false, value = "ifTaxi") String ifTaxi,
        @RequestParam(required = true, value = "accessibleType") String accessibleType,
        @RequestParam(required = false, value = "picture") String picture) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            map = zhuancheService
                .updateCarTypeV4up(id, name, sequence, picture, ifTaxi, accessibleType);

            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    // 修改车辆类型
    @RequestMapping(value = "updateCarType", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateCarType(@RequestParam("id") Long id,
        @RequestParam("name") String name, @RequestParam("sequence") Integer sequence,
        @RequestParam("areaId") Long areaId,
        @RequestParam(required = false, value = "picture") String picture) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            int i = zhuancheService.updateCarType(id, name, sequence, areaId, picture);
            if (i != 0) {
                map.put("success", true);
                map.put("message", "修改成功!");
            } else {
                map.put("success", false);
                map.put("message", "修改失败!");
            }
            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    // 修改车辆
    @RequestMapping(value = "updateCar", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateCar(Car car, String pictureAddress,
        String provincialStr) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            Map<String, Object> map = new HashMap<String, Object>();
            try {
                if (StringUtils.isNotBlank(car.getCarNumber())) {
                    car.setCarNumber(car.getCarNumber().toUpperCase());
                }
                if (!CarNumberUtils.isCarNumber(car.getCarNumber())) {
                    map.put("success", false);
                    map.put("message", "车牌号码格式不正确!");
                    return map;
                }
                car.setProvincial(provincialStr);
                car.setPicture(pictureAddress);
                map = zhuancheService.updateCar(car);


            } catch (Exception e) {
                e.printStackTrace();
                map.put("success", false);
                map.put("message", "修改失败!");
            }

            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    // 查询保险到期的车辆
    @RequestMapping(value = "getInsuranceTime", method = RequestMethod.GET)
    public @ResponseBody
    List<Car> getInsuranceTime() {
        Subject subject = SecurityUtils.getSubject();
        List<Car> list = new ArrayList<Car>();
        if (subject.isPermitted("zhuan")) {
            list = zhuancheService.queryByInsuranceTime();
        }
        return list;
    }

    @RequestMapping(value = "getInsuranceTimeLong", method = RequestMethod.GET)
    public @ResponseBody
    Long getInsuranceTimeLong() {
        Subject subject = SecurityUtils.getSubject();
        Long count = null;
        if (subject.isPermitted("zhuan")) {
            count = zhuancheService.queryByInsuranceTimeLong();
        }
        return count;
    }

    // 查询年检到期的车辆
    @RequestMapping(value = "getOverhaulTime", method = RequestMethod.GET)
    public @ResponseBody
    List<Car> getOverhaulTimee() {
        Subject subject = SecurityUtils.getSubject();
        List<Car> list = new ArrayList<Car>();
        if (subject.isPermitted("zhuan")) {
            list = zhuancheService.queryByOverhaulTime();
        }
        return list;
    }

    @RequestMapping(value = "getOverhaulTimeLong", method = RequestMethod.GET)
    public @ResponseBody
    Long getOverhaulTimeeLong() {
        Subject subject = SecurityUtils.getSubject();
        Long count = null;
        if (subject.isPermitted("zhuan")) {
            count = zhuancheService.queryByOverhaulTimeLong();
        }
        return count;
    }

    @RequestMapping(value = "zhuanHeatMapData", method = RequestMethod.POST)
    public @ResponseBody
    List<PointVo> zhuanHeatMapData(
        @RequestParam(required = false, value = "year") Integer year,
        @RequestParam(required = false, value = "month") Integer month) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuan")) {
            Calendar calendar = Calendar.getInstance();

            if (null == year) {
                year = calendar.get(Calendar.YEAR);
            }
            if (null == month) {
                month = calendar.get(Calendar.MONTH);
            }

            List<Order> list = zhuancheService.findMonthOrder(year, month);
            List<Order> matched = new LinkedList<Order>();
            List<PointVo> processed = new LinkedList<PointVo>();

            for (int i = 0; i < list.size(); i++) {

                Order order = list.get(i);

                if (matched.contains(order)) {
                    continue;
                }

                PointVo pointVo = new PointVo();
                if (order.getStartLat() != null && order.getStartLng() != null) {
                    pointVo.lat = order.getStartLat();
                    pointVo.lng = order.getStartLng();
                }

                pointVo.count = 1;
                processed.add(pointVo);

                for (int j = i + 1; j < list.size(); j++) {

                    Order order2 = list.get(j);

                    if (matched.contains(order2)) {
                        continue;
                    }

                    PointVo pointVo2 = new PointVo();
                    if (order2.getStartLat() != null && order2.getStartLng() != null) {
                        pointVo2.lat = order2.getStartLat();
                        pointVo2.lng = order2.getStartLng();
                    }
                    if (pointVo.isSameLocation(pointVo, pointVo2)) { // 相同位置
                        pointVo.count++;
                        matched.add(order2);// 加入已匹配列表
                    }

                }

            }

            return processed;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("zhuanMemberOrderData")
    public @ResponseBody
    PageVo<MemberOrderVo> zhuanMemberOrderData(
        @RequestParam(required = false, value = "type") Integer type,
        @RequestParam(required = false, value = "gradeId") Long gradeId,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "companyId") Long companyId) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("zhuan")) {
            Date start = null;
            Date end = null;

            if (!StringUtils.isEmpty(startTime)) {

                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }

            if (!StringUtils.isBlank(endTime)) {

                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            PageVo<MemberOrderVo> result = null;
            if (principal.isCompanyType()) {
                result = zhuancheService.zhuanMemberOrder(start, end, companyId, gradeId, type);
            } else {
                result = zhuancheService
                    .zhuanMemberOrder(start, end, principal.getCompanyId(), gradeId,
                        type);
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 查询催单记录
     */
    @RequestMapping(value = "getCuidanOrders", method = RequestMethod.GET)
    public @ResponseBody
    List<Order> getCuidanOrders() {
        Subject subject = SecurityUtils.getSubject();
        List<Order> cuidanOrders = new ArrayList<Order>();
        ServiceSetting serviceSetting = ServiceUtil.checkOpen();
        if (serviceSetting.isZhuanche() && subject.isPermitted("zhuan")) {
            cuidanOrders = zhuancheService.selectCuidan();
        }
        return cuidanOrders;
    }

    /**
     * 关闭催单提示框
     */
    @RequestMapping(value = "closeCuidan", method = RequestMethod.POST)
    public @ResponseBody
    void closeCuidan(Long orderId) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuan")) {
            zhuancheService.closeCuidan(orderId);
        }
    }

    // 派单
    @RequestMapping(value = "paidan", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Map<String, Object> paidan(Long driverId, Long orderId) {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Map<String, Object> map = new HashMap<String, Object>();
        Driver driver1 = driverService.findOne(driverId);
        if (subject.isPermitted("zhuanPaidan")) {
            Driver driver = driverService.findOne(driverId);
            if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
                map.put("success", false);
                map.put("message", "该服务人员状态非空闲，不能派单");
                return map;
            }

            Order order = zhuancheService.findOne(orderId);
            if (order.getStatus() != 0) {
                map.put("success", false);
                map.put("message", "订单状态错误，不能派单");
                return map;
            }
            Car car = zhuancheService.findCar(driver.getCarId());
            if (car == null) {
                map.put("success", false);
                map.put("message", "该服务人员没有专车车辆，不能派单");
                return map;
            }
            // CarType carType =
            // zhuancheService.findCarType(order.getCarTypeId());
            // if(null != carType && !carType.getTypeName().equals("出租车")){
            // if(!car.getCarTypeId().equals(order.getCarTypeId())){
            // map.put("success", false);
            // map.put("message", "该服务人员的车辆类型和订单车辆类型不一致");
            // return map;
            // }
            // }

            if (!driver.getDriverJobType().equals(Driver.DriverJobType.all)) {
                if (!driver.getDriverJobType().contains(Driver.DriverJobType.zhuanche.toString())) {
                    map.put("success", false);
                    map.put("message", "该服务人员不能派专车订单");
                    return map;
                }
            }

            // Set<String> cantBookDriverIdSet = zhuancheService.findBookDrivers();
            // Boolean noBook = cantBookDriverIdSet.contains(driverId.toString());
            // if (noBook) {
            // map.put("success", false);
            // map.put("message", "该服务人员不能派预约用车订单");
            // return map;
            // }

            Map<String, Object> map2 = getDriverBusy(driver.getId());
            Boolean success = (Boolean) map2.get("success");
            if (!success) {
                return map2;
            }

            Result<Order> result = zhuancheService.paidan(driver, order, principal.getUsername());

            if (result.isSuccess()) {
                map.put("success", true);
                String detail = "【%s】派专车单【" + order.getOrderNo() + "】";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                // 派单事件
                ZhuanOrderPaidanEvent paidanEvent = new ZhuanOrderPaidanEvent(order.getId());
                applicationEventMulticaster.multicastEvent(paidanEvent);
            } else {
                map.put("success", false);
                map.put("message", result.getMessage());
            }
            return map;
        } else {
            map.put("success", false);
            map.put("message", "您没有该权限");
            return map;
        }
    }

    // 判断服务人员状态
    public Map<String, Object> getDriverBusy(Long employId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean busy = true;
        String message = "";
        Integer code = 0;
        if (employId != null) {
            try {
                ServiceSetting serviceSetting = ServiceUtil.checkOpen();

                if (serviceSetting.isDaijia()) {
                    Long daijiaAmount = orderService.countActivedOrdersByDriver(employId);
                    if (daijiaAmount > 0) {
                        System.err.println(employId + "还有未完成的代驾工单,不能派单");
                        busy = false;
                        message = "还有未完成的代驾工单,不能派单";
                        code = -1;
                    }
                }

                // if(serviceSetting.isZhuanche()){
                // Long
                // zhuancheAmount=zhuancheService.countActivedOrdersByDriver(employId);
                // if(zhuancheAmount>0){
                // System.err.println(employId+"还有未完成的专车工单,不能派单");
                // busy=false;
                // message="还有未完成的专车工单,不能派单";
                // code=-2;
                // }
                // }

                if (serviceSetting.isPaotui()) {
                    Long paotuiAmount = errandService.countBusyAmount(employId);
                    if (paotuiAmount > 0) {
                        System.err.println(employId + "还有未完成的跑腿工单,不能派单");
                        busy = false;
                        message = "还有未完成的跑腿工单,不能派单";
                        code = -3;
                    }
                }

                if (serviceSetting.isFreight()) {
                    Long huoyunAmount = freightService.countActivedOrdersByDriver(employId);
                    if (huoyunAmount > 0) {
                        System.err.println(employId + "还有未完成的货运工单,不能派单");
                        busy = false;
                        message = "还有未完成的货运工单,不能派单";
                        code = -4;
                    }
                }

                if (serviceSetting.isZhuanxian()) {
                    Long huoyunAmount = zhuanxianService.countActivedOrdersByDriver(employId);
                    if (huoyunAmount > 0) {
                        System.err.println(employId + "还有未完成的专线工单,不能派单");
                        busy = false;
                        message = "还有未完成的专线工单,不能派单";
                        code = -5;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            busy = false;
        }
        map.put("success", busy);
        map.put("message", message);
        map.put("code", code);
        return map;
    }

    @RequestMapping("exportZhuanMemberOrder")
    public void exportMemberOrder(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "type") Integer type,
        @RequestParam(required = false, value = "gradeId") Long gradeId, HttpServletRequest req,
        HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("zhuan")) {
            Date start = null;
            Date end = null;
            if (!StringUtils.isEmpty(startTime)) {

                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }

            if (!StringUtils.isBlank(endTime)) {

                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }

            PageVo<MemberOrderVo> list = zhuancheService
                .zhuanMemberOrder(start, end, companyId, gradeId,
                    type);

            String[] head = new String[4];
            List<List<String>> rowlist = new ArrayList<List<String>>();

            head[0] = ("客户");
            head[1] = ("所属公司");
            head[2] = ("订单完成数量（单）");
            head[3] = ("订单完成金额（元）");
            for (MemberOrderVo a : list.getContent()) {
                List<String> celllist = new ArrayList<String>();

                celllist.add(a.getName() + "-" + a.getPhone());
                celllist.add(a.getCompanyName());
                celllist.add(a.getFinishNums() + "");
                celllist.add(a.getMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());

                rowlist.add(celllist);

            }

            ExcelUtil.export(req, response, head, rowlist);
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "pointDetails", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> pointDetails(Long id) {

        Subject subject = SecurityUtils.getSubject();

        Map<String, Object> map = new HashMap<String, Object>();

        if (subject.isPermitted("zhuan")) {

            List<OrderLocation> orderLocations = new ArrayList<OrderLocation>();
            List<OrderLocation> orderLocations_dr = new ArrayList<OrderLocation>();
            List<OrderLocation> orderLocations_pa = new ArrayList<OrderLocation>();
            List<OrderLocation> orderLocations_dr_ca = new ArrayList<OrderLocation>();
            List<OrderLocationMany> orderLocationManys = orderLocationManyService
                .selectByOrderTypeAndOrderId(OrderLocation.OrderType.zhuanche, id);
            List<OrderLocationMany> orderLocationManys_dr = orderLocationManyService
                .selectByOrderTypeAndOrderId(OrderLocation.OrderType.zhuanche_dr, id);
            List<OrderLocationMany> orderLocationManys_pa = orderLocationManyService
                .selectByOrderTypeAndOrderId(OrderLocation.OrderType.zhuanche_pa, id);
            List<OrderLocationMany> orderLocationManys_dr_ca = orderLocationManyService
                .selectByOrderTypeAndOrderId(OrderLocation.OrderType.zhuanche_dr_ca, id);
            orderLocationManyToOrderLocation(orderLocations, orderLocationManys);
            orderLocationManyToOrderLocation(orderLocations_dr, orderLocationManys_dr);
            orderLocationManyToOrderLocation(orderLocations_pa, orderLocationManys_pa);
            orderLocationManyToOrderLocation(orderLocations_dr_ca, orderLocationManys_dr_ca);
            // List<OrderLocation> orderLocations =
            // orderLocationService.selectByOrderTypeAndOrderId(OrderLocation.OrderType.zhuanche,id);

            if (CollectionUtils.isEmpty(orderLocations)) {
                List<OrderLngLat> maplist = new ArrayList<OrderLngLat>();
                OrderOrbit orderOrbit = zhuancheService.findOrbitByOrderId(id);
                if (null != orderOrbit) {
                    maplist = orderOrbit.getLngAndLat();
                }
                if (!CollectionUtils.isEmpty(maplist)) {
                    for (OrderLngLat orderLngLat : maplist) {
                        OrderLocation orderLocation = new OrderLocation();
                        orderLocation.setLatitude(orderLngLat.getLat());
                        orderLocation.setLongitude(orderLngLat.getLng());
                        orderLocations.add(orderLocation);
                    }
                }
            }

            double runDistance = 0;
            double waitDistance = 0;
            if (!CollectionUtils.isEmpty(orderLocations)) {
                Double lastLng = null;
                Double lastLat = null;
                Integer lastRun = null;

                Double firstLng = null;
                Double firstLat = null;

                for (OrderLocation orderLocation : orderLocations) {

                    Double thisLng = null;
                    Double thisLat = null;
                    Integer thisRun = null;

                    thisLng = orderLocation.getLongitude();
                    thisLat = orderLocation.getLatitude();
                    thisRun = orderLocation.getRun();

                    if (null == firstLng && null == firstLat) {
                        firstLng = thisLng;
                        firstLat = thisLat;
                    }

                    if (null != lastLng && null != lastLat && null != thisLng && null != thisLat) {
                        if (null != lastRun && null != thisRun) {
                            if ((lastRun == 1 && thisRun == 1) || (lastRun == 0 && thisRun == 1)) {
                                runDistance += Distance
                                    .doubleVal(lastLat, lastLng, thisLat, thisLng);
                            } else {
                                waitDistance += Distance
                                    .doubleVal(lastLat, lastLng, thisLat, thisLng);
                            }
                        }

                    }

                    lastLng = thisLng;
                    lastLat = thisLat;
                    lastRun = thisRun;

                }
                map.put("orderLocations", orderLocations);
                map.put("orderLocations_dr", orderLocations_dr);
                map.put("orderLocations_pa", orderLocations_pa);
                map.put("firstLng", firstLng);
                map.put("firstLat", firstLat);
            }

            map.put("runDistance",
                new BigDecimal(runDistance).setScale(1, BigDecimal.ROUND_HALF_UP));
            map.put("waitDistance",
                new BigDecimal(waitDistance).setScale(1, BigDecimal.ROUND_HALF_UP));
            map.put("success", true);
            return map;
        } else {
            map.put("success", false);
            map.put("message", "您没有该权限");
        }

        return map;

    }

    private void orderLocationManyToOrderLocation(List<OrderLocation> orderLocations, List<OrderLocationMany> orderLocationManys) {
        if (!CollectionUtils.isEmpty(orderLocationManys)) {
            OrderLocationMany orderLocationMany = orderLocationManys.get(0);
            Gson gson = new Gson();
            List<OrderLocationGroup> locs = gson.fromJson(orderLocationMany.getJsonLocs(),
                new TypeToken<List<OrderLocationGroup>>() {
                }.getType());

            if (!CollectionUtils.isEmpty(locs)) {
                for (OrderLocationGroup og : locs) {
                    OrderLocation orderLocation = new OrderLocation();
                    orderLocation.setSortId(og.getId());
                    orderLocation.setLatitude(og.getLatitude());
                    orderLocation.setLongitude(og.getLongitude());
                    orderLocation.setRadius(og.getRadius());
                    orderLocation.setDirection(og.getDirection());
                    orderLocation.setLocType(og.getLocType());
                    orderLocation.setLocDate(new Date(og.getLocDate()));
                    orderLocation.setRun(og.getRun());
                    orderLocations.add(orderLocation);
                }
            }
        }
    }

    @RequestMapping("importCar")
    @ResponseBody
    public Map<String, Object> importCar(@RequestParam("carExcel") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();
            Workbook wb = null;
            try {
                wb = new HSSFWorkbook(file.getInputStream());
            } catch (Exception e) {
                wb = new XSSFWorkbook(file.getInputStream());
            }
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum();// 得到总行数
            Row row = sheet.getRow(0);
            int colNum = row.getPhysicalNumberOfCells(); // 列的数量
            Pattern pattern = Pattern
                .compile("^([\\u4e00-\\u9fa5]{1}[A-z]{1}[A-z_0-9]{5})|([A-z]{1,2}[0-9]{4})$");
            List<Integer> carNumberIndexs = new LinkedList<>();
            List<Integer> drivingIndexs = new LinkedList<>();
            List<Integer> dateIndex = new LinkedList<>();

            List<Car> list = new LinkedList<>();
            for (int i = 1; i <= rowNum; i++) {
                row = sheet.getRow(i);
                int j = 0;
                Car car = new Car();
                if (colNum >= 8) {// 如果使用的是监管平台上传模板，导入以下默认值
                    // 车牌颜色
                    car.setPlateColor("蓝色");
                    // 车辆归属：
                    car.setDriverProType("ZY");
                    // 燃料类型：
                    car.setFuel("A");
                    // 核定载客：
                    car.setPermitted("5");
                    // 运价类型：
                    car.setRateType(0);
                    // 运营状态：
                    car.setVehicleStatus("YY");
                }
                boolean flag = false;
                boolean dateFlag = false;
                while (j < colNum) {
                    if (row == null || row.getCell(j) == null) {
                        flag = true;
                    } else {
                        String str = ExcelUtil.getCellFormatValue(row.getCell(j)).trim();
                        car.setCompanyName(principal.getCompanyAbbreviation());
                        car.setCompanyId(principal.getCompanyId());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                        switch (j) {
                            case 0:// A车辆名称
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    car.setCarName(str);
                                }

                                break;
                            case 1:// B车牌号码
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    if (pattern.matcher(str).matches()) {
                                        car.setCarNumber(str.toUpperCase());
                                    } else {
                                        carNumberIndexs.add(i);
                                    }
                                }
                                break;
                            case 2:// C车辆类型
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    car.setCarTypeName(str);
                                }
                                break;
                            case 3:// D行驶里程
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setDrivingDistance(Double.valueOf(str));
                                    } catch (Exception e) {
                                        drivingIndexs.add(i);
                                    }
                                }
                                break;
                            case 4:// E购车日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setBuyTime(sdf.parse(str));
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 5:// F下次年检日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setOverhaulTime(sdf.parse(str));
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 6:// G保险到期日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setInsuranceTime(sdf.parse(str));
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 7:// H保险公司
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setInsurer(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 8:// I保险号
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setInsuranceNo(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 9:// J保险类型，如“机动车交通事故责任强制保险”
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setInsType(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 10:// K保险金额
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        if (!StringUtils.isBlank(str)) {
                                            car.setInsMoney(Double.valueOf(str));
                                        }
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 11:// L保险生效日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        if (!StringUtils.isBlank(str)) {
                                            car.setInsValidTime(sdf.parse(str));
                                        }
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 12:// M车辆厂牌(见行驶证品牌型号汉字内容)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setBrand(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 13:// N车辆类型(见行驶证)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setVehicleType(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 14:// O车辆型号(见行驶证品牌型号字母数字内容)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setVehicleModel(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 15:// P所属车主(见行驶证所有人)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setOwner(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 16:// Q车身颜色(如：黑色)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setBodyColor(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 17:// R车辆排量(如：2000)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setDisplacement(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 18:// S详细地址(如：XX街道XXX号)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setAddress(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 19:// T发动机号（见行驶证）
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setEngineNo(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 20:// U车辆识别VIN（见行驶证）
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setVin(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 21:// V车辆注册日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        if (!StringUtils.isBlank(str)) {
                                            car.setRegistrationTime(sdf.parse(str));
                                        }
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 22:// W运输证发证机构（XX市交通运输管理局）
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setTaxiAgency(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 23:// X运输证经营区域（XX市）
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setTaxiRegion(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 24:// Y运输证编号（X交运管许可X字XXXXXXXXXXXX号）
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setTaxiNo(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 25:// Z运输证激活日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        if (!StringUtils.isBlank(str)) {
                                            car.setTaxiRegisterTime(sdf.parse(str));
                                        }
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 26:// AA运输证有效日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        if (!StringUtils.isBlank(str)) {
                                            car.setValidTime(sdf.parse(str));
                                        }
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 27:// AB运输证失效日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        if (!StringUtils.isBlank(str)) {
                                            car.setInvalidTime(sdf.parse(str));
                                        }
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 28:// AC发票打印设备序号
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setDeviceSerial(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 29:// AD定位装置品牌
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setDeviceBrand(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 30:// AE定位装置型号
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setDeviceModel(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 31:// AF卫星定位装置IMEI号
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        car.setGpsIMEI(str);
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                            case 32:// AG定位装置安装日期(2016/12/01)
                                if (StringUtils.isBlank(str)) {
                                    flag = true;
                                } else {
                                    try {
                                        if (!StringUtils.isBlank(str)) {
                                            car.setDeviceInstallTime(sdf.parse(str));
                                        }
                                    } catch (Exception e) {
                                        dateFlag = true;
                                    }
                                }
                                break;
                        }
                    }

                    j++;
                }
                if (flag) {
                    continue;
                }
                if (dateFlag) {
                    dateIndex.add(i + 1);
                } else {
                    list.add(car);
                }

            }

            if (list.size() > 2001) {
                response.put("msg", "导入数量过大,请限制数量在2000条以内");
                response.put("rowNum", list.size());
                return response;
            }
            if (list.size() <= 0) {
                response.put("msg", "Excel文件内容不正确");
                response.put("rowNum", list.size());
                return response;
            }
            if (CollectionUtils.isEmpty(carNumberIndexs) && CollectionUtils.isEmpty(drivingIndexs)
                && CollectionUtils.isEmpty(dateIndex)) {
                if (!CollectionUtils.isEmpty(list)) {
                    Gson gson = new Gson();
                    String data = gson.toJson(list);
                    Result<Map<String, Object>> mapResult = zhuancheService.batchCreate(data);
                    if (mapResult.isSuccess()) {
                        response.put("success", true);
                        response.putAll(mapResult.getResult());
                    }
                }
            }
            response.put("drivingIndexs", drivingIndexs);
            response.put("dateIndex", dateIndex);
            response.put("carNumberIndexs", carNumberIndexs);
            return response;
        } catch (Exception ex) {
            ex.printStackTrace();
            response.put("msg", "导入失败");
            response.put("rowNum", ex.getMessage());
            return response;
        }

    }

    @RequestMapping(value = "zhuancheCarTemplate")
    public void exportOrder(HttpServletRequest req, HttpServletResponse response)
        throws IOException,
        ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        String[] head = null;
        if (subject.isPermitted("zhuan")) {
            ServiceSetting serviceSetting = ServiceUtil.checkOpen();
            if (!serviceSetting.isJgpt() || !settingUtils.get()
                .isUpPlatformInfo()) {// 若监管平台权限或上传开关----关闭----，使用以下模板
                head = new String[7];
                head[0] = ("（*必填）车辆名称");
                head[1] = ("（*必填）车牌号码");
                head[2] = ("（*必填）车辆类型");
                head[3] = ("（*必填）行驶里程");
                head[4] = ("（*必填）购车日期(2016/12/01)");
                head[5] = ("（*必填）下次年检日期(2016/12/01)");
                head[6] = ("（*必填）保险到期日期(2016/12/01)");
            } else {// 若监管平台权限----开启----，使用以下模板
                head = new String[33];
                head[0] = ("（*必填）车辆名称");
                head[1] = ("（*必填）车牌号码");
                head[2] = ("（*必填）车辆类型");
                head[3] = ("（*必填）行驶里程");
                head[4] = ("（*必填）购车日期(2016/12/01)");
                head[5] = ("（*必填）下次年检日期(2016/12/01)");
                head[6] = ("（*必填）保险到期日期(2016/12/01)");
                head[7] = ("保险公司");
                head[8] = ("保险号");
                head[9] = ("保险类型，如“机动车交通事故责任强制保险”");
                head[10] = ("保险金额");
                head[11] = ("保险生效日期(2016/12/01)");
                head[12] = ("车辆厂牌(见行驶证品牌型号汉字内容)");
                head[13] = ("车辆类型(见行驶证)");
                head[14] = ("车辆型号(见行驶证品牌型号字母数字内容)");
                head[15] = ("所属车主(见行驶证所有人)");
                head[16] = ("车身颜色(如：黑色)");
                head[17] = ("车辆排量(如：2000)");
                head[18] = ("详细地址(如：XX街道XXX号)");
                head[19] = ("发动机号（见行驶证）");
                head[20] = ("车辆识别VIN（见行驶证）");
                head[21] = ("车辆注册日期(2016/12/01)");
                head[22] = ("运输证发证机构（XX市交通运输管理局）");
                head[23] = ("运输证经营区域（XX市）");
                head[24] = ("运输证编号（X交运管许可X字XXXXXXXXXXXX号）");
                head[25] = ("运输证激活日期(2016/12/01)");
                head[26] = ("运输证有效日期(2016/12/01)");
                head[27] = ("运输证失效日期(2016/12/01)");
                head[28] = ("发票打印设备序号");
                head[29] = ("定位装置品牌");
                head[30] = ("定位装置型号");
                head[31] = ("卫星定位装置IMEI号");
                head[32] = ("定位装置安装日期(2016/12/01)");
            }

            HSSFWorkbook wb = new HSSFWorkbook();

            // 创建Excel的工作sheet,对应到一个excel文档的tab
            Sheet sheet = wb.createSheet("sheet1");

            HSSFFont font_title = wb.createFont();
            font_title.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font_title.setFontHeight((short) 300);
            HSSFCellStyle cellStyleTitle = wb.createCellStyle();
            cellStyleTitle.setFont(font_title);
            cellStyleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            if (null != head) {
                // 创建Excel的sheet的一行
                Row row = sheet.createRow(0);

                for (int i = 0; i < head.length; i++) {
                    // 创建一个Excel的单元格
                    Cell cell = row.createCell(i);
                    cell.setCellValue(head[i]);
                    cell.setCellStyle(cellStyleTitle);
                    if (i > 3) {
                        sheet.setColumnWidth(i, 40 * 256);
                    } else {
                        sheet.setColumnWidth(i, 20 * 256);
                    }

                    // sheet.autoSizeColumn(i);
                }
            }

            List<CarType> carTypes = zhuancheService.queryCarTypeV4up(principal.getCompanyId());
            String[] strs = new String[carTypes.size()];
            for (int i = 0; i < strs.length; i++) {
                strs[i] = carTypes.get(i).getTypeName();
            }
            CellRangeAddressList regions = new CellRangeAddressList(1, 65535, 2, 2);
            DVConstraint constraint = DVConstraint.createExplicitListConstraint(strs);

            HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
            sheet.addValidationData(dataValidation);
            String bathPath = WebUtils.getRealPath(req.getSession().getServletContext(), "/");
            String filestr = "template/excel/专车车辆导入模板.xls";
            File f = new File(bathPath, filestr);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            FileOutputStream os = new FileOutputStream(f);
            wb.write(os);
            os.close();

            // 下載
            InputStream fis = new BufferedInputStream(new FileInputStream(f));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("专车车辆导入模板.xls", "UTF-8"));
            response.addHeader("Content-Length", "" + f.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("getCheckCarAllInfo")
    @ResponseBody
    public Map<String, Object> getCheckCarAllInfo(HttpServletRequest req) {
        Map<String, Object> resp = new HashMap<>();
        HttpSession session = req.getSession();
        resp.put("reportAllCheck", session.getAttribute("reportAllCheck"));
        resp.put("reportAllData", session.getAttribute("reportAllData"));
        return resp;
    }

    @RequestMapping("getupCarAllInfo")
    @ResponseBody
    public Map<String, Object> getupCarAllInfo(HttpServletRequest req) {
        Map<String, Object> data = new HashMap<>();
        data.put("success", req.getSession().getAttribute("success"));
        data.put("upCarAllInfo", req.getSession().getAttribute("upCarAllInfo"));
        return data;
    }

    // 保存保险
    @RequestMapping(value = "createInsurance", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createInsurance(Insurance insurance) throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanCar")) {
            return zhuancheService.createInsurance(insurance);
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping("{carId}/insurance")
    public ModelAndView insurance(@PathVariable("carId") Long carId) {
        Subject subject = SecurityUtils.getSubject();

        ModelAndView mv = new ModelAndView();
        mv.setViewName("zhuanche/insurancelist");

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Page<Insurance> page = zhuancheService.queryInsuranceByPage(carId);

        mv.addObject("page", page);
        mv.addObject("carId", carId);

        return mv;

    }

    @RequestMapping("deletetInsurance")
    @ResponseBody
    public Result deletetInsurance(@RequestParam("id") Long id) {
        Result result = new Result();
        try {
            zhuancheService.deletetInsurance(id);
            result.setSuccess(true);
            result.setMessage("删除成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("服务器开小差了,请稍后再试!");
        }
        return result;
    }

    @RequestMapping("report")
    @ResponseBody
    public Map<String, Object> reportAll(HttpServletRequest req) throws FileNotFoundException {
        Map<String, Object> resp = new HashMap<>();
        try {
            final int rows = 50;
            final HttpSession session = req.getSession();
            final String basePath = WebUtils.getRealPath(req.getSession().getServletContext(), "/");

            session.setAttribute("reportAllCheck", false);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Page<Car> cars = zhuancheService.findCarByIds(null, 0, rows);
                    final int totalPages = cars.getTotalPages();
                    Map<String, Object> data = new HashMap<String, Object>();
                    for (Car obj : cars.getContent()) {
                        StringBuilder sb = new StringBuilder();
                        if (StringUtils.isBlank(obj.getVehicleType())) {
                            sb.append("车型不能为空,");
                        }
                        if (obj.getRegistrationTime() == null) {
                            sb.append("车辆注册日期不能为空,");
                        }
                        if (StringUtils.isBlank(obj.getCarNumber())) {
                            sb.append("车牌号不能为空,");
                        }
                        if (StringUtils.isBlank(obj.getTaxiNo())) {
                            sb.append("网约车车辆运输证号不能为空,");
                        }
                        CarType carType = zhuancheService.findCarType(obj.getCarTypeId());
                        if (carType == null || StringUtils.isBlank(carType.getTypeName())) {
                            sb.append("车辆类型不能为空,");
                        }
                        if (StringUtils.isBlank(basePath) || StringUtils
                            .isBlank(obj.getPicture())) {
                            sb.append("车辆照片不能为空,");
                        } else {
                            try {
                                File file = new File(basePath, obj.getPicture());
                            } catch (Exception e) {
                                sb.append("车辆照片不正确,");
                            }
                        }
                        if (obj.getDrivingDistance() == null) {
                            sb.append("车辆行驶里程不能为空,");
                        }

                        if (StringUtils.isBlank(obj.getDeviceSerial())) {
                            sb.append("发票打印设备序号不能为空,");
                        }
                        if (StringUtils.isBlank(obj.getDeviceBrand())) {
                            sb.append("定位装置品牌不能为空,");
                        }

                        if (StringUtils.isBlank(obj.getDeviceModel())) {
                            sb.append("定位装置型号不能为空,");
                        }
                        if (obj.getDeviceInstallTime() == null) {
                            sb.append("定位装置安装日期不能为空,");
                        }
                        if (sb.length() > 0) {
                            data.put(obj.getCarNumber(), sb.toString());
                        }
                    }
                    for (int i = 1; i < totalPages; i++) {
                        Page<Car> carByIds = zhuancheService.findCarByIds(null, i, rows);
                        for (Car obj : carByIds.getContent()) {
                            StringBuilder sb = new StringBuilder();
                            if (StringUtils.isBlank(obj.getVehicleType())) {
                                sb.append("车型不能为空,");
                            }

                            if (obj.getRegistrationTime() == null) {
                                sb.append("车辆注册日期不能为空,");
                            }
                            if (StringUtils.isBlank(obj.getCarNumber())) {
                                sb.append("车牌号不能为空,");
                            }
                            if (StringUtils.isBlank(obj.getTaxiNo())) {
                                sb.append("网约车车辆运输证号不能为空,");
                            }
                            CarType carType = zhuancheService.findCarType(obj.getCarTypeId());
                            if (carType == null || StringUtils.isBlank(carType.getTypeName())) {
                                sb.append("车辆类型不能为空,");
                            }
                            if (StringUtils.isBlank(basePath) || StringUtils
                                .isBlank(obj.getPicture())) {
                                sb.append("车辆照片不能为空,");
                            } else {

                                try {
                                    File file = new File(basePath, obj.getPicture());
                                } catch (Exception e) {
                                    sb.append("车辆照片不正确,");
                                }
                            }
                            if (obj.getDrivingDistance() == null) {
                                sb.append("车辆行驶里程不能为空,");
                            }

                            if (StringUtils.isBlank(obj.getDeviceSerial())) {
                                sb.append("发票打印设备序号不能为空,");
                            }
                            if (StringUtils.isBlank(obj.getDeviceBrand())) {
                                sb.append("定位装置品牌不能为空,");
                            }

                            if (StringUtils.isBlank(obj.getDeviceModel())) {
                                sb.append("定位装置型号不能为空,");
                            }
                            if (obj.getDeviceInstallTime() == null) {
                                sb.append("定位装置安装日期不能为空,");
                            }
                            if (sb.length() > 0) {
                                data.put(obj.getCarNumber(), sb.toString());
                            }
                        }
                    }
                    session.setAttribute("reportAllData", data);

                    session.setAttribute("reportAllCheck", true);

                }
            }).start();
            resp.put("code", 0);
            resp.put("message", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("code", 500);
            resp.put("message", "失败");
        }
        return resp;
    }

    @RequestMapping("checkCarInfo")
    @ResponseBody
    public Map<String, Object> checkCarInfo(Long[] ids, HttpServletRequest req) {
        Page<Car> page = zhuancheService.findCarByIds(ids, null, null);
        String basePath = null;
        final HttpSession session = req.getSession();
        try {
            basePath = WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        List<Car> content = page.getContent();

        Map<String, Object> msg = new HashMap<String, Object>();
        msg.put("success", false);
        session.setAttribute("checkCarInfo", msg);
        for (Car obj : content) {
            StringBuilder sb = new StringBuilder();
            if (StringUtils.isBlank(obj.getVehicleType())) {
                sb.append("车型不能为空,");
            }

            if (obj.getRegistrationTime() == null) {
                sb.append("车辆注册日期不能为空,");
            }
            if (StringUtils.isBlank(obj.getCarNumber())) {
                sb.append("车牌号不能为空,");
            }
            if (StringUtils.isBlank(obj.getTaxiNo())) {
                sb.append("网约车车辆运输证号不能为空,");
            }
            CarType carType = zhuancheService.findCarType(obj.getCarTypeId());
            if (carType == null || StringUtils.isBlank(carType.getTypeName())) {
                sb.append("车辆类型不能为空,");
            }
            if (StringUtils.isBlank(basePath) || StringUtils.isBlank(obj.getPicture())) {
                sb.append("车辆照片不能为空,");
            } else {
                if (!new File(basePath, obj.getPicture()).exists()) {
                    sb.append("车辆照片不正确,");
                }
            }
            if (obj.getDrivingDistance() == null) {
                sb.append("车辆行驶里程不能为空,");
            }

            if (StringUtils.isBlank(obj.getDeviceSerial())) {
                sb.append("发票打印设备序号不能为空,");
            }
            if (StringUtils.isBlank(obj.getDeviceBrand())) {
                sb.append("定位装置品牌不能为空,");
            }

            if (StringUtils.isBlank(obj.getDeviceModel())) {
                sb.append("定位装置型号不能为空,");
            }
            if (obj.getDeviceInstallTime() == null) {
                sb.append("定位装置安装日期不能为空,");
            }
            if (sb.length() > 0) {
                msg.put(obj.getCarNumber(), sb.toString());
            }
        }
        msg.put("success", true);
        session.setAttribute("checkCarInfo", msg);

        Map<String, Object> data = new HashMap<>();
        data.put("code", 0);
        data.put("message", "成功");
        return data;
    }

    @RequestMapping("getCheckCarInfo")
    @ResponseBody
    public Map<String, Object> getCheckCarInfo(HttpServletRequest req) {

        return (Map<String, Object>) req.getSession().getAttribute("checkCarInfo");
    }

    @RequestMapping("upCarInfo")
    @ResponseBody
    public Map<String, Object> upCarInfo(Long[] ids, HttpServletRequest req)
        throws FileNotFoundException {
        return zhuancheService.upCarInfo(ids,
            WebUtils.getRealPath(req.getSession().getServletContext(), "/"));
    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    private boolean isAreaIdExist(List<Area> areaList, CarTypeCompany carTypeCompany, long id,
        boolean flag) {
        for (Area area : areaList) {
            // 如果遍历到立即tangzu收费标准还存在收费标准列表，终止循环,不改变值(flag=true)
            if (id == area.getId()) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
